<?php

namespace app\index\controller;

use excel\ExcelDownload;
use excel\ExcelReader;
use PHPExcel;
use PHPExcel_Style_Alignment;
use PHPExcel_Style_Border;
use PHPExcel_Style_Fill;
use PHPExcel_Writer_Excel5;
use think\Db;
use think\Validate;

class Ashippingguide extends Common
{
    //导购薪资级别管理
    public function index()
    {
        //查询条件
        $where = $this->request->post();
        $this->assign('where', $where);
        $where = self::str($where);
        $page = empty($where['pages']) ? 1 : $where['pages'];
        $list = empty($where['limts']) ? 10 : $where['limts'];
        unset($where['pages']);
        unset($where['limts']);
        //总数量，总金额，总条数
        $count = Db::table('bx_guide_salaryLevel')
            ->where($where)
            ->count();
        $this->assign('count', $count);
        //分页
        $maxpage = ceil($count / $list);
        $page = $page < $maxpage ? $page : $maxpage;
        $page = $page > 1 ? $page : 1;
        $start = ($page - 1) * $list;
        $this->assign('page', $page);
        $this->assign('maxpage', $maxpage);
        $this->assign('limit', $list);
        //数据
        $data = Db::table('bx_guide_salaryLevel')
            ->where($where)->order('id', 'desc')
            ->limit($start, $list)
            ->select();
        $this->assign('data', $data);
        return $this->fetch();
    }

    //替换_
    public function str($where)
    {
        $tmp = [];
        $like = [
            'name' => ['like', '%val%'],
            'livingCity' => ['like', '%val%'],
            'mainNet' => ['like', '%val%'],
            'salaryLevel' => ['like', '%val%'],
            'cityType' => ['like', '%val%'],
            'a_name' => ['like', '%val%'],
            'b_title' => ['like', '%val%'],
            'p_title' => ['like', '%val%'],
            'n_title' => ['like', '%val%'],
            'o_title' => ['like', '%val%'],
            'b_stuff' => ['like', '%val%'],
            'a_nowState' => ['like', '%val%'],
            'a_mainNet' => ['like', '%val%'],
            'a_postType' => ['like', '%val%'],
            'b_salaryLevel' => ['like', '%val%'],
            'a_indexes' => ['like', '%val%'],
            'c_title' => ['like', '%val%'],
            'a_BPartyName' => ['like', '%val%'],
            'a_APartyName' => ['like', '%val%'],
            'a_indexes' => ['like', '%val%'],
            'a_phone' => ['like', '%val%'],
            'a_IDNo' => ['like', '%val%'],
            'pages' => 'val',
            'limts' => 'val',

        ];
        foreach ($where as $key => $val) {
            if (!empty($val)) {
                if (isset($where['a_endDate']) && ($where['a_endDate'] == 1)) {
                    $tmp[] = ['exp', '(DATE_SUB(`endDate`,INTERVAL 2 MONTH) < CURDATE()) AND (CURDATE() <= `endDate`)'];
                    unset($where['a_endDate']);
                }
                if (isset($where['a_fyDate']) && isset($where['a_fyDate1'])) {
                    if ($where['a_fyDate'] && $where['a_fyDate1']) {
                        $tmp['a.signDate'] = ['between', [$where['a_fyDate'], $where['a_fyDate1']]];
                    } else if ($where['a_fyDate']) {
                        $tmp['a.signDate'] = ['>=', $where['a_fyDate']];
                    } else if ($where['a_fyDate1']) {
                        $tmp['a.signDate'] = ['<=', $where['a_fyDate1']];
                    }
                }
                foreach ($like as $k => $v) {
                    if ($key == $k) {
                        $tmp[preg_replace('/\_/', '.', $key, 1)] = str_replace('val', $val, $v);
                    }
                }

            }
            unset($tmp['items']);

        }
        return $tmp;
    }

//编辑数据查询
    public
    function editP()
    {
        $id = $this->request->get('id');
        if ($id) {
            if ($data = Db::table('bx_guide_salaryLevel')->where('id', $id)->find()) {
                return json([
                    "success" => true,
                    'data' => $data
                ]);
            } else {
                return json([
                    "success" => false,
                    'mag' => '网络错误！请重试'
                ]);
            }
        } else {
            echo '主键错误！';
        }
    }

//新增\修改薪资级别
    public
    function add()
    {
        $data = $this->request->post();
        $validate = new Validate([
            ['salaryLevel', 'require', '薪资级别名称必须'],
            ['basePay', 'require', '基本工资必须'],
            ['cityType', 'require', '所属城市类别必须'],
        ]);
        if ($validate->check($data)) {
            if (!$data['id']) {
                if (Db::table('bx_guide_salaryLevel')->insert($data)) {
                    $this->redirect('ashippingguide/index');
                } else {
                    return json([
                        "success" => false,
                        'mag' => '网络错误！请重试'
                    ]);
                }
            } else {
                Db::table('bx_guide_salaryLevel')->where('id', $data['id'])->update($data);
                $this->redirect('ashippingguide/index');
            }
        } else {
            return json([
                "success" => $validate->check($data),
                "msg" => $validate->getError()
            ]);
        }
    }


//删除单条数据
    public
    function del()
    {
        $id = $this->request->get('id');
        if ($id) {
            if (Db::table('bx_guide_salaryLevel')->where('id', $id)->delete()) {
                return json([
                    "success" => true
                ]);
            } else {
                return json([
                    "success" => false,
                    'mag' => '网络错误！请重试'
                ]);
            }
        } else {
            echo '主键错误！';
        }
    }

//导入文件
    public
    function import()
    {
        return $this->fetch();
    }

//导入
    public
    function upload()
    {
        // 获取表单上传文件
        $file = request()->file('file');
        // 移动到框架应用根目录/public/uploads/bx_guide 目录下
        $info = $file->validate(['ext' => 'xls,xlsx', 'size' => 105678])->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'bx_guide');
        if ($info) {
            // 成功上传后 获取上传信息
            $data = self::testExcel($info->getSaveName());
            echo "<script>top.sweetAlert('" . $data['msg'] . "','','" . $data['success'] . "');parent.location.reload();</script>";
        } else {
            // 上传失败获取错误信息
            echo "<script>top.sweetAlert('" . $file->getError() . "','','warning');</script>";
        }
    }

    /**
     * excel导入示例
     */
    public
    function testExcel($file)
    {
        $url = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'bx_guide' . DS . $file;
        $reader = new ExcelReader($url);
        $titlesMap = [
            'cityType' => '城市类别',
            'salaryLevel' => '导购薪资级别名称',
            'basePay' => '基本工资(元/月)',
        ];
        // 是否提供titlesMap 返回的数据结构不一致
        $data = $reader->exec($titlesMap);
        if ($data) {
            unset($data[0]);
            foreach ($data as $key => $val) {
                $is_empty = 0;
                foreach ($val as $k => $v) {
                    if (!trim($v)) {
                        $is_empty++;
                    }
                }
                if ($is_empty == count($val)) unset($data[$key]);
            }
            if ($data) {
                $cityType = ['一类城市', '二类城市', '三类城市'];
                $cityType1 = implode(',', $cityType);
                $validate = new Validate([
                    ['cityType', 'require|in:' . $cityType1, '城市类别必须|城市类别不存在'],
                    ['salaryLevel', 'require', '导购薪资级别名称必须'],
                    ['basePay', 'require', '基本工资必须'],
                ]);
                $off = 1;
                foreach ($data as $key => $val) {
                    if ($validate->check($val)) {
                        $off = 1;
                    } else {
                        $off = 0;
                        break;
                    }
                }

                if ($off === 1) {
                    foreach ($data as $key => $val) {
                        if ($val['cityType'] == '一类城市') {
                            $tmp[] = $val['salaryLevel'];
                            $tmp1 = array_count_values($tmp);
                        } else if ($val['cityType'] == '二类城市') {
                            $tmp2[] = $val['salaryLevel'];
                            $tmp21 = array_count_values($tmp2);
                        } else {
                            $tmp3[] = $val['salaryLevel'];
                            $tmp31 = array_count_values($tmp3);
                        }
                    }
                    if (self::count($tmp1) == 3) {
                        if (self::count($tmp21) == 3) {
                            if (self::count($tmp31) == 3) {
                                if (Db::table('bx_guide_salaryLevel')->insertAll($data)) {
                                    return [
                                        "success" => 'success',
                                        'msg' => '上传文件成功'
                                    ];
                                } else {
                                    return [
                                        "success" => 'warning',
                                        'msg' => '网络错误！请重试'
                                    ];
                                }
                            } else {
                                return [
                                    'success' => false,
                                    'msg' => '三类城市下导购薪资级别名称重复！'
                                ];
                            }
                        } else {
                            return [
                                'success' => false,
                                'msg' => '二类城市下导购薪资级别名称重复！'
                            ];
                        }
                    } else {
                        return [
                            'success' => false,
                            'msg' => '一类城市下导购薪资级别名称重复！'
                        ];
                    }
                } else {
                    return [
                        "success" => 'warning',
                        "msg" => $validate->getError()
                    ];
                }
            } else {
                return [
                    "success" => 'warning',
                    'msg' => '请填充数据'
                ];
            }
        } else {
            return [
                "success" => 'warning',
                'msg' => '网络错误！请重试'
            ];
        }
    }

    private
    function count($data)
    {
        foreach ($data as $key => $val) {
            if ($val == 1) {
                return $off = 3;
            } else {
                return $off = 4;
            }
        }
    }

//所有导购人员档案管理
    public
    function allGuide()
    {
        //查询条件
        $where = $this->request->post();
        $this->assign('where', $where);
        $where = self::str($where);
        $page = empty($where['pages']) ? 1 : $where['pages'];
        $list = empty($where['limts']) ? 10 : $where['limts'];
        unset($where['pages']);
        unset($where['limts']);
        //总数量，总金额，总条数
        $count = Db::table('bx_guide_user')->alias('a')
            ->join('cg_net b', 'a.mainNet_id = b.id', 'LEFT')
            ->join('cg_market_zoning p', 'b.zoning = p.id', 'LEFT')//营销区
            ->join('cg_market_provice n', 'b.provice = n.id', 'LEFT')//营销省
            ->join('cg_market_city o', 'b.city = o.id', 'LEFT')//营销市
            ->join('cg_system e', 'b.system_id = e.id', 'LEFT')//系统表
            ->where($where)
            ->count();
        $this->assign('count', $count);
        //分页
        $maxpage = ceil($count / $list);
        $page = $page < $maxpage ? $page : $maxpage;
        $page = $page > 1 ? $page : 1;
        $start = ($page - 1) * $list;
        $this->assign('page', $page);
        $this->assign('maxpage', $maxpage);
        $this->assign('limit', $list);
        //数据
        $data = Db::table('bx_guide_user')->alias('a')
            ->join('cg_net b', 'a.mainNet_id = b.id', 'LEFT')
            ->join('cg_market_zoning p', 'b.zoning = p.id', 'LEFT')//营销区
            ->join('cg_market_provice n', 'b.provice = n.id', 'LEFT')//营销省
            ->join('cg_market_city o', 'b.city = o.id', 'LEFT')//营销市
            ->join('cg_system e', 'b.system_id = e.id', 'LEFT')//系统表
            ->field("a.name,b.title wd,p.title yq,n.title ys,o.title yshi,b.stuff wdfz,e.title xt,
            a.phone,CONCAT(a.livingProvince,'-',a.livingCity,'-',a.livingCounty,'-',a.livingAddress) address,
            a.IDNo,CONCAT(a.houseProvince,'-',a.houseCity,'-',a.houseCounty,'-',a.houseAddress) address1,(case
            when a.nowState = 0 then '在职'
            when a.nowState = 1 then '使用'
            when a.nowState = 2 then '离职'
            end) state,a.quitDate,a.id,a.des")
            ->where($where)->order('a.id', 'desc')
            ->limit($start, $list)
            ->select();
        foreach ($data as $key => $val) {
            if ($val['wdfz']) {
                $data[$key]['wdfz'] = implode(',', Db::name('employee')->where("id in (" . implode(',', unserialize($val['wdfz'])) . ")")->column('em_name'));
            }
        }
        $this->assign('data', $data);
        return $this->fetch();
    }

//新增导购人员档案
    public
    function addGuide()
    {
        return $this->fetch();
    }

    public
    function addguideform()
    {
        $data = $this->request->post();
        if (!$data['entryDate']) $data['entryDate'] = NULL;
        if (!$data['justDate']) $data['justDate'] = NULL;
        if (!$data['birthDate']) $data['birthDate'] = NULL;
        $name = Db::table('bx_guide_user')->column('id,name');
        $name1 = implode(',', $name);
        $validate = new Validate([
            ['name', 'require|notIn:' . $name1, '姓名必须|姓名已存在'],
            ['workNumber', 'require', '工牌号必须'],
            ['mainNet', 'require', '主网点必须'],
            ['postType', 'require', '岗位类型必须'],
            ['entryDate', 'require|date', '入职日期必须|日期格式'],
        ]);
        if ($validate->check($data)) {
            //人员userPhoto，工牌照片workPhoto，身份证IDPhoto，银行卡bankPhoto
            $userPhoto = request()->file('userPhoto');
            if (!empty($userPhoto)) {
//                // 移动到框架应用根目录/public/uploads/bx_guide 目录下
                $info1 = $userPhoto->validate(['ext' => 'png,jpg,jpeg,gif'])->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'bx_guide_user');
                if ($info1) {
                    // 成功上传后 获取上传信息
                    $data['userPhoto'] = $info1->getSaveName();
                } else {
                    // 上传失败获取错误信息
                    echo "<script>top.sweetAlert('" . $userPhoto->getError() . "','','success');history.go(-1);</script>";
                }
            }
            $workPhoto = request()->file('workPhoto');
            if (!empty($workPhoto)) {
//                // 移动到框架应用根目录/public/uploads/bx_guide 目录下
                $info2 = $workPhoto->validate(['ext' => 'png,jpg,jpeg,gif'])->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'bx_guide_user');
                if ($info2) {
                    // 成功上传后 获取上传信息
                    $data['workPhoto'] = $info2->getSaveName();
                } else {
                    // 上传失败获取错误信息
                    echo "<script>top.sweetAlert('" . $workPhoto->getError() . "','','success');history.go(-1);</script>";
                }
            }
            $IDPhoto = request()->file('IDPhoto');
            if (!empty($IDPhoto)) {
//                // 移动到框架应用根目录/public/uploads/bx_guide 目录下
                $info3 = $IDPhoto->validate(['ext' => 'png,jpg,jpeg,gif'])->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'bx_guide_user');
                if ($info3) {
                    // 成功上传后 获取上传信息
                    $data['IDPhoto'] = $info3->getSaveName();
                } else {
                    // 上传失败获取错误信息
                    echo "<script>top.sweetAlert('" . $IDPhoto->getError() . "','','success');history.go(-1);</script>";
                }
            }
            $bankPhoto = request()->file('bankPhoto');
            if (!empty($bankPhoto)) {
//                // 移动到框架应用根目录/public/uploads/bx_guide 目录下
                $info4 = $bankPhoto->validate(['ext' => 'png,jpg,jpeg,gif'])->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'bx_guide_user');
                if ($info4) {
                    // 成功上传后 获取上传信息
                    $data['bankPhoto'] = $info4->getSaveName();
                } else {
                    // 上传失败获取错误信息
                    echo "<script>top.sweetAlert('" . $bankPhoto->getError() . "','','success');history.go(-1);</script>";
                }
            }
            $tmp = $data['exampleInputFile'];
            unset($data['exampleInputFile']);
            if ($id = Db::table('bx_guide_user')->insertGetId($data)) {
                $BaseData = new Ashippingmanagement2();
                $BaseData->file($tmp, 'bx_guide_user', $id);
                unset($tmp);
                $this->redirect('ashippingguide/allGuide');
            }
        } else {
            echo "<script>top.sweetAlert('" . $validate->getError() . "','','warning');history.go(-1);</script>";
        }

    }

    public
    function editguideform()
    {
        $data = $this->request->post();
        if (!$data['entryDate']) $data['entryDate'] = NULL;
        if (!$data['justDate']) $data['justDate'] = NULL;
        if (!$data['birthDate']) $data['birthDate'] = NULL;
        if ($data['id']) {
            $validate = new Validate([
                ['name', 'require', '姓名必须'],
                ['workNumber', 'require', '工牌号必须'],
                ['mainNet', 'require', '主网点必须'],
                ['postType', 'require', '岗位类型必须'],
                ['entryDate', 'require|date', '入职日期必须|日期格式'],
            ]);
            if ($validate->check($data)) {
                //人员userPhoto，工牌照片workPhoto，身份证IDPhoto，银行卡bankPhoto
                $userPhoto = request()->file('userPhoto');
                if (!empty($userPhoto)) {
//                // 移动到框架应用根目录/public/uploads/bx_guide 目录下
                    $info1 = $userPhoto->validate(['ext' => 'png,jpg,jpeg,gif'])->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'bx_guide_user');
                    if ($info1) {
                        // 成功上传后 获取上传信息
                        $data['userPhoto'] = $info1->getSaveName();
                    } else {
                        // 上传失败获取错误信息
                        echo "<script>top.sweetAlert('" . $userPhoto->getError() . "','','success');history.go(-1);</script>";
                    }
                }
                $workPhoto = request()->file('workPhoto');
                if (!empty($workPhoto)) {
//                // 移动到框架应用根目录/public/uploads/bx_guide 目录下
                    $info2 = $workPhoto->validate(['ext' => 'png,jpg,jpeg,gif'])->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'bx_guide_user');
                    if ($info2) {
                        // 成功上传后 获取上传信息
                        $data['workPhoto'] = $info2->getSaveName();
                    } else {
                        // 上传失败获取错误信息
                        echo "<script>top.sweetAlert('" . $workPhoto->getError() . "','','success');history.go(-1);</script>";
                    }
                }
                $IDPhoto = request()->file('IDPhoto');
                if (!empty($IDPhoto)) {
//                // 移动到框架应用根目录/public/uploads/bx_guide 目录下
                    $info3 = $IDPhoto->validate(['ext' => 'png,jpg,jpeg,gif'])->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'bx_guide_user');
                    if ($info3) {
                        // 成功上传后 获取上传信息
                        $data['IDPhoto'] = $info3->getSaveName();
                    } else {
                        // 上传失败获取错误信息
                        echo "<script>top.sweetAlert('" . $IDPhoto->getError() . "','','success');history.go(-1);</script>";
                    }
                }
                $bankPhoto = request()->file('bankPhoto');
                if (!empty($bankPhoto)) {
//                // 移动到框架应用根目录/public/uploads/bx_guide 目录下
                    $info4 = $bankPhoto->validate(['ext' => 'png,jpg,jpeg,gif'])->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'bx_guide_user');
                    if ($info4) {
                        // 成功上传后 获取上传信息
                        $data['bankPhoto'] = $info4->getSaveName();
                    } else {
                        // 上传失败获取错误信息
                        echo "<script>top.sweetAlert('" . $bankPhoto->getError() . "','','success');history.go(-1);</script>";
                    }
                }
                $BaseData = new Ashippingmanagement2();
                $BaseData->file($data['exampleInputFile'], 'bx_guide_user', $data['id']);
                unset($data['exampleInputFile']);
                self::compare2('bx_guide_user', $data);
                Db::table('bx_guide_user')->where('id', $data['id'])->update($data);
                $this->redirect('ashippingguide/allGuide');
            } else {
                echo "<script>top.sweetAlert('" . $validate->getError() . "','','warning');history.go(-1);</script>";
            }
        } else {
            echo '主键错误';
        }

    }

//编辑导购人员
    public
    function editGuide()
    {
        $id = $this->request->get('id');
        if ($id) {
            $data = Db::table('bx_guide_user')->where('id', $id)->find();
            $this->assign('data', $data);
            //附件
            $BaseData = new Ashippingmanagement2();
            $uploadify = $BaseData->fileSelect($id, 'bx_guide_user');
            $this->assign('uploadify', $uploadify);
            return $this->fetch();
        } else {
            echo '主键缺失！';
        }
    }

//验证姓名是否唯一
    public
    function checkName()
    {
        //fieldId,fieldValue
        $data = $this->request->get();
        $str = Db::table('bx_guide_user')->where('name', trim($data['fieldValue']))->find();
        return json([$data['fieldId'], !$str]);
    }

//验证姓名是否唯一
    public
    function checkGuideName()
    {
        //fieldId,fieldValue
        $data = $this->request->get();
        $str = Db::table('bx_guide_post')->where('guideName', trim($data['fieldValue']))->find();
        return json([$data['fieldId'], !$str]);
    }


//选择网点
    public
    function selectMainNet()
    {
        return $this->fetch();
    }

//按照经销商返回网点树
    public
    function netTree()
    {
//        $jid = $this->request->param('keyword');
        $where = [];

        $data = Db::table('cg_net')->alias("n")
            ->join("cg_system s", "n.system_id=s.id")
//            ->join("cg_jxs j", "s.jxs=j.id")
//            ->where("j.id=$jid")
            ->field('n.title as name,n.id')->select();
        $data2 = [];
        foreach ($data as $k => $v) {
            $temp = [];
            $temp['name'] = $v['name'];
            $temp['id'] = $v['id'];
            $temp["chkDisabled"] = false;
            $data2[] = $temp;
        }
        echo json_encode($data2);
    }

//品牌
    public
    function selectpinpai()
    {
        return $this->fetch();
    }

//品类
    public
    function selectpinlei()
    {
        return $this->fetch();
    }


//导购薪资级别管理
    public
    function salaryLevel()
    {
        //查询条件
        $where = $this->request->post();
        $this->assign('where', $where);
        $where = self::str($where);
        $page = empty($where['pages']) ? 1 : $where['pages'];
        $list = empty($where['limts']) ? 10 : $where['limts'];
        unset($where['pages']);
        unset($where['limts']);
        //总数量，总金额，总条数
        $count = Db::table('bx_guide_user')->alias('a')
            ->join('bx_guide_salaryLevel b', 'a.salarylevel_id = b.id', 'LEFT')
            ->where($where)
            ->count();
        $this->assign('count', $count);
        //分页
        $maxpage = ceil($count / $list);
        $page = $page < $maxpage ? $page : $maxpage;
        $page = $page > 1 ? $page : 1;
        $start = ($page - 1) * $list;
        $this->assign('page', $page);
        $this->assign('maxpage', $maxpage);
        $this->assign('limit', $list);
        //数据
        $data = Db::table('bx_guide_user')->alias('a')
            ->join('bx_guide_salaryLevel b', 'a.salarylevel_id = b.id', 'LEFT')
            ->field("a.id,a.name,a.mainNet,(case
            when a.postType = 0 then '全职'
            when a.postType = 1 then '兼职'
            when a.postType = 2 then '专职'
            end) postType,b.salaryLevel")
            ->where($where)->order('a.id', 'desc')
            ->limit($start, $list)
            ->select();
        $this->assign('data', $data);
        //薪资级别
        $zxjb = Db::table('bx_guide_salaryLevel')->field('id,salaryLevel')->select();
        $this->assign('zxjb', $zxjb);
        return $this->fetch();
    }

//详情
    public
    function infoP()
    {
        $id = $this->request->get('id');
        if ($id) {
            $data = Db::table('bx_guide_user')->alias('a')
                ->join('bx_guide_salaryLevel b', 'a.salarylevel_id = b.id', 'LEFT')
                ->field('a.id aid,a.name,b.*')
                ->where('a.id', $id)->find();
            return json($data);
        } else {
            echo '主键错误';
        }
    }

//编辑薪资级别
    public
    function editLevel()
    {
        $data = $this->request->post();
        if ($data['id']) {
            Db::table('bx_guide_user')->where('id', $data['id'])->update($data);
        }
        $this->redirect('ashippingguide/salaryLevel');
    }

//薪资薪资基本资料
    public
    function basePay()
    {
        //查询条件
        $where = $this->request->post();
        $this->assign('where', $where);
        $where = self::str($where);
        $page = empty($where['pages']) ? 1 : $where['pages'];
        $list = empty($where['limts']) ? 10 : $where['limts'];
        unset($where['pages']);
        unset($where['limts']);
        //总数量，总金额，总条数
        $count = Db::table('bx_guide_user')
            ->where($where)
            ->count();
        $this->assign('count', $count);
        //分页
        $maxpage = ceil($count / $list);
        $page = $page < $maxpage ? $page : $maxpage;
        $page = $page > 1 ? $page : 1;
        $start = ($page - 1) * $list;
        $this->assign('page', $page);
        $this->assign('maxpage', $maxpage);
        $this->assign('limit', $list);
        //数据
        $data = Db::table('bx_guide_user')
            ->field("id,name,mainNet,(CASE 
            when nowState = 0 then '在职'
            when nowState = 1 then '试用'
            when nowState = 2 then '离职'
             END) nowState,openingBank,bankAccount")
            ->where($where)->order('id', 'desc')
            ->limit($start, $list)
            ->select();
        $this->assign('data', $data);
        return $this->fetch();
    }

//编辑个人银行信息
    public
    function editBankP()
    {
        $id = $this->request->get('id');
        if ($id) {
            $data = Db::table('bx_guide_user')
                ->field("id,name,openingBank,bankAccount")
                ->where('id', $id)
                ->find();
            return json($data);
        }
    }

//编辑个人信息
    public
    function bankEdit()
    {
        $data = $this->request->post();
        if ($data['id']) {
            Db::table('bx_guide_user')->where('id', $data['id'])->update($data);
        }
        $this->redirect('ashippingguide/basePay');
    }

//导购岗位管理
    public
    function guidepost()
    {
        //查询条件
        $where = $this->request->post();
        $this->assign('where', $where);
        $where = self::str($where);
        $page = empty($where['pages']) ? 1 : $where['pages'];
        $list = empty($where['limts']) ? 10 : $where['limts'];
        unset($where['pages']);
        unset($where['limts']);
        //总数量，总金额，总条数
        $count = Db::table('bx_guide_post')->alias('a')
            ->join('employee b', 'a.createUser = b.id', 'LEFT')
            ->join('employee c', 'a.modifyUser = c.id', 'LEFT')
            ->where($where)
            ->count();
        $this->assign('count', $count);
        //分页
        $maxpage = ceil($count / $list);
        $page = $page < $maxpage ? $page : $maxpage;
        $page = $page > 1 ? $page : 1;
        $start = ($page - 1) * $list;
        $this->assign('page', $page);
        $this->assign('maxpage', $maxpage);
        $this->assign('limit', $list);
        //数据
        $data = Db::table('bx_guide_post')->alias('a')
            ->join('employee b', 'a.createUser = b.id', 'LEFT')
            ->join('employee c', 'a.modifyUser = c.id', 'LEFT')
            ->field('a.id,a.guideName,b.em_name createUser,a.createDate,c.em_name modifyUser,a.modifyDate')
            ->where($where)->order('sort', 'desc')
            ->limit($start, $list)
            ->select();
        $this->assign('data', $data);
        $sort = Db::table('bx_guide_post')->max('sort');
        if (!$sort) {
            $sort = 1;
        } else {
            $sort = $sort + 1;
        };
        $this->assign('sort', $sort);
        return $this->fetch();
    }

//添加导购岗位
    public
    function postAdd()
    {
        $data = $this->request->post();
        $guideName = Db::table('bx_guide_post')->column('id,guideName');
        $guideName1 = implode(',', $guideName);
        $validate = new Validate([
            ['guideName', 'require|notIn:' . $guideName1, '导购岗位名称必须|导购岗位名称已存在'],
            ['sort', 'require', '次序必须']
        ]);
        if ($validate->check($data)) {
            if ($data['id']) {
                $data['modifyDate'] = date('Y-m-d H:i:s');
                $data['modifyUser'] = session('employee_id');
                Db::table('bx_guide_post')->where('id', $data['id'])->update($data);
                $this->redirect('ashippingguide/guidepost');
            } else {
                $data['createDate'] = date('Y-m-d H:i:s');
                $data['createUser'] = session('employee_id');
                if (Db::table('bx_guide_post')->insert($data)) {
                    $this->redirect('ashippingguide/guidepost');
                } else {
                    echo '网络错误，重试！';
                }
            }
        } else {
            return json([
                "success" => $validate->check($data),
                "msg" => $validate->getError()
            ]);
        }
    }

//导购岗位详情
    public
    function postEditP()
    {
        $id = $this->request->get('id');
        if ($id) {
            $data = Db::table('bx_guide_post')->where('id', $id)->find();
            return json([
                'success' => true,
                'data' => $data,
            ]);
        } else {
            return json([
                'success' => false,
            ]);
        }
    }

//删除导购岗位
    public
    function postDel()
    {
        $id = $this->request->get('id');
        if ($id) {
            if (Db::table('bx_guide_post')->where('id', $id)->delete()) {
                return json([
                    'success' => true,
                ]);
            } else {
                return json([
                    'success' => false,
                ]);
            };
        } else {
            return json([
                'success' => false,
            ]);
        }
    }

//导入
    public
    function uploadPost()
    {
        // 获取表单上传文件
        $file = request()->file('file');
        // 移动到框架应用根目录/public/uploads/bx_wd 目录下
        $info = $file->validate(['ext' => 'xls,xlsx', 'size' => 105678])->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'bx_guide');
        if ($info) {
            //成功上传后 获取上传信息
            $data = self::testExcel2($info->getSaveName());
            if ($data['success'] == 'success') {
                echo "<script>top.sweetAlert('" . $data['msg'] . "','','" . $data['success'] . "');history.go(-1);</script>";
            } else {
                echo "<script>top.sweetAlert('" . $data['msg'] . "','','" . $data['success'] . "');</script>";
            }
        } else {
            //上传失败获取错误信息
            echo "<script>top.sweetAlert('" . $file->getError() . "','','warning');</script>";
        }
    }

    /**
     * excel导入示例
     */
    public
    function testExcel2($file)
    {
        $url = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'bx_guide' . DS . $file;
        $reader = new ExcelReader($url);
        $titlesMap = [
            'guideName' => '导购岗位名称',
            'sort' => '显示次序',
        ];
        // 是否提供titlesMap 返回的数据结构不一致
        $data = $reader->exec($titlesMap);
        if ($data) {
            unset($data[0]);
            foreach ($data as $key => $val) {
                $is_empty = 0;
                foreach ($val as $k => $v) {
                    if (!trim($v)) {
                        $is_empty++;
                    }
                }
                if ($is_empty == count($val)) unset($data[$key]);
            }
            if ($data) {
                $guideName = Db::table('bx_guide_post')->column('id,guideName');
                $guideName1 = implode(',', $guideName);
                $validate = new Validate([
                    ['guideName', 'require|notIn:' . $guideName1, '导购岗位名称必须|导购岗位名称已存在'],
                    ['sort', 'require', '次序必须']
                ]);
                $off = 1;
                foreach ($data as $key => $val) {
                    $data[$key]['createDate'] = date('Y-m-d H:i:s');
                    $data[$key]['createUser'] = session('employee_id');
                    if ($validate->check($val)) {
                        $off = 1;
                    } else {
                        $off = 0;
                        break;
                    }
                }
                if ($off === 1) {
                    if (Db::table('bx_guide_post')->insertAll($data)) {
                        return [
                            "success" => 'success',
                            'msg' => '上传文件成功'
                        ];
                    } else {
                        return [
                            "success" => 'warning',
                            'msg' => '网络错误！请重试'
                        ];
                    }
                } else {
                    return [
                        "success" => 'warning',
                        "msg" => $validate->getError()
                    ];
                }
            } else {
                return [
                    "success" => 'warning',
                    'msg' => '请填充数据'
                ];
            }
        } else {
            return [
                "success" => 'warning',
                'msg' => '网络错误！请重试'
            ];
        }
    }

//导出一级出货数据
    public
    function export()
    {
        $str = '导购岗位';
//        $titles = ['姓名', '年龄', '性别', '身高'];
        // titles格式也可以如下
        $titles = [
            'guideName' => '导购岗位名称',
            'createUser' => '创建人',
            'createDate' => '创建时间',
            'modifyDate' => '修改人',
            'modifyUser' => '修改时间',
        ];
        $data = Db::table('bx_guide_post')->alias('a')
            ->join('employee b', 'a.createUser = b.id', 'LEFT')
            ->join('employee c', 'a.modifyUser = c.id', 'LEFT')
            ->field('a.guideName,b.em_name createUser,a.createDate,a.modifyDate,c.em_name modifyUser')
            ->select();
        $data[] = [
            'title' => $str,
        ];
        $excel = new ExcelDownload();
        $excel->exec($data, $titles, '岗位管理数据', ['sheet' => ['rowHeight' => 20]], 2);
    }


//导购劳动合同管理
    public
    function labourContract()
    {
        //查询条件
        $where = $this->request->post();
        $this->assign('where', $where);
        $where = self::str($where);
        $page = empty($where['pages']) ? 1 : $where['pages'];
        $list = empty($where['limts']) ? 10 : $where['limts'];
        unset($where['pages']);
        unset($where['limts']);
        //总数量，总金额，总条数
        $count = Db::table('bx_guide_labour_contract')->alias('a')
            ->join('bx_guide_user b', 'a.BPartyName_id = b.id')
            ->join('cg_net c', 'b.mainNet_id = c.id', 'LEFT')
            ->where($where)
            ->count();
        $this->assign('count', $count);
        //分页
        $maxpage = ceil($count / $list);
        $page = $page < $maxpage ? $page : $maxpage;
        $page = $page > 1 ? $page : 1;
        $start = ($page - 1) * $list;
        $this->assign('page', $page);
        $this->assign('maxpage', $maxpage);
        $this->assign('limit', $list);
        //数据
        $data = Db::table('bx_guide_labour_contract')->alias('a')
            ->join('bx_guide_user b', 'a.BPartyName_id = b.id')
            ->join('cg_net c', 'b.mainNet_id = c.id', 'LEFT')
            ->field("a.id,a.indexes,a.BPartyName,(case 
            when b.postType = 0 then '全职'
            when b.postType = 1 then '兼职'
            when b.postType = 2 then '专职'
             end) postType,a.APartyName,b.mainNet_id,c.title mainNet,a.signDate,a.endDate,a.signNum,if(a.returnContract = 0,'x','√') returnContract,(case
            when b.nowState = 0 then '在职'
            when b.nowState = 1 then '使用'
            when b.nowState = 2 then '离职'
            end) state")
            ->where($where)->order('a.id', 'desc')
            ->limit($start, $list)
            ->select();
        $this->assign('data', $data);
        return $this->fetch();
    }

//新增劳动合同
    public
    function labourAdd()
    {
        $data = $this->request->post();
        if ($data['id']) {
            //更新
            Db::table('bx_guide_labour_contract')->where('id', $data['id'])->update($data);
        } else {
            //新增
            Db::table('bx_guide_labour_contract')->insert($data);
        }
        $this->redirect('Ashippingguide/labourContract');
    }

//编辑劳动合同
    public
    function labourEdit()
    {
        $id = $this->request->get('id');
        if ($id) {
            $data = Db::table('bx_guide_labour_contract')->where('id', $id)->find();
            return json($data);
        }
    }

//删除劳动合同
    public
    function labourDel()
    {
        $id = $this->request->get('id');
        if ($id) {
            Db::table('bx_guide_labour_contract')->where('id', $id)->delete();
            return json(['success' => true]);
        }
    }

//导出劳动合同
    public
    function exportLabourContract()
    {
        $user = Db::table('employee')->where('id', session('employee_id'))->value('em_name');
        $str = '注：本表单由销路通软件导出，导出时间：' . date('Y-m-d H:i:s') . '；导出人：' . $user;
        $str1 = '导购人员劳动合同';
//        $titles = ['姓名', '年龄', '性别', '身高'];
        // titles格式也可以如下
        $titles = [
            'indexes' => '索引',
            'BPartyName' => '乙方姓名',
            'postType' => '岗位类型',
            'APartyName' => '甲方名称',
            'mainNet' => '乙方所属网点名称',
            'signDate' => '合同起始日',
            'endDate' => '合同到期日',
            'signNum' => '签署次数',
            'returnContract' => '已返回合同',
            'state' => '状态',
        ];
        $data = Db::table('bx_guide_labour_contract')->alias('a')
            ->join('bx_guide_user b', 'a.BPartyName_id = b.id')
            ->join('cg_net c', 'b.mainNet_id = c.id', 'LEFT')
            ->field("a.indexes,a.BPartyName,(case 
            when b.postType = 0 then '全职'
            when b.postType = 1 then '兼职'
            when b.postType = 2 then '专职'
             end) postType,a.APartyName,c.title mainNet,a.signDate,a.endDate,a.signNum,if(a.returnContract = 0,'x','√') returnContract,(case
            when b.nowState = 0 then '在职'
            when b.nowState = 1 then '使用'
            when b.nowState = 2 then '离职'
            end) state")
            ->select();
        $data[] = [
            'title' => $str1,
            'sub' => $str,
        ];
        $excel = new ExcelDownload();
        $excel->exec($data, $titles, '劳动合同数据', ['sheet' => ['rowHeight' => 20]], 3);
    }

//导入劳动合同
    public
    function labourimport()
    {
        return $this->fetch();
    }

//导入劳动合同
    public
    function uploadLabour()
    {
        // 获取表单上传文件
        $file = request()->file('file');
        // 移动到框架应用根目录/public/uploads/bx_guide 目录下
        $info = $file->validate(['ext' => 'xls,xlsx', 'size' => 105678])->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'bx_guide');
        if ($info) {
            // 成功上传后 获取上传信息
            $data = self::testExcel1($info->getSaveName());
            echo "<script>top.sweetAlert('" . $data['msg'] . "','','" . $data['success'] . "');parent.location.reload();</script>";
        } else {
            // 上传失败获取错误信息
            echo "<script>top.sweetAlert('" . $file->getError() . "','','warning');</script>";
        }
    }

    /**
     * excel导入示例
     */
    public
    function testExcel1($file)
    {
        $url = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'bx_guide' . DS . $file;
        $reader = new ExcelReader($url);
        $titlesMap = [
            'indexes',// '索引',
            'contractName',// '合同名称',
            'APartyName',// '甲方名称',
            'BPartyName',// '乙方姓名',
            'signDate',// '合同起始日',
            'endDate',// '合同到期日',
            'returnContract',// '已返回合同',
            'address',// '合同通讯地址',
            'des',// '备注',
        ];
        // 是否提供titlesMap 返回的数据结构不一致
        $data = $reader->exec();
        if ($data) {
            unset($data[0]);
            unset($data[1]);
            unset($data[2]);
            foreach ($data as $key => $val) {
                $is_empty = 0;
                foreach ($val as $k => $v) {
                    if (!trim($v)) {
                        $is_empty++;
                    }
                }
                if ($is_empty == count($val)) unset($data[$key]);
            }
            foreach ($data as $key => $val) {
                $tmp[] = array_combine($titlesMap, $val);
            }
            if ($tmp) {
                $APartyName = ['广州销路通软件公司', 'A公司', '测试甲方名称', 'B公司'];
                $APartyName1 = implode(',', $APartyName);
                $BPartyName = Db::table('bx_guide_user')->where('nowState', 'not in', '2')->column('id,name');
                $BPartyName1 = implode(',', $BPartyName);
                $returnContract = ['是', '否'];
                $returnContract1 = implode(',', $returnContract);

                $off = 1;
                foreach ($tmp as $key => $val) {
                    $validate = new Validate([
                        ['indexes', 'require', '索引必须'],
                        ['contractName', 'require', '合同名称必须'],
                        ['APartyName', 'require|in:' . $APartyName1, '甲方名称必须|甲方名称不存在'],
                        ['BPartyName', 'require|in:' . $BPartyName1, '乙方名称必须|乙方名称不存在'],
                        ['signDate', 'require|date|before:' . $tmp[$key]['endDate'], '合同开始时间必须|合同开始时间时间格式|合同开始时间小于结束时间'],
                        ['endDate', 'require|date|after:' . $tmp[$key]['signDate'], '合同结束时间必须|合同结束时间时间格式|合同结束时间大于开始时间'],
                        ['returnContract', 'require|in:' . $returnContract1, '已返回合同必须|已返回合同填写是或否'],
                    ]);
                    $tmp[$key]['BPartyName_id'] = array_search($tmp[$key]['BPartyName'], $BPartyName);
                    if ($validate->check($val)) {
                        $off = 1;
                    } else {
                        $off = 0;
                        break;
                    }
                }
                if ($off == 1) {
                    if (Db::table('bx_guide_labour_contract')->insertAll($tmp)) {
                        return [
                            "success" => 'success',
                            'msg' => '上传文件成功'
                        ];
                    } else {
                        return [
                            "success" => 'warning',
                            'msg' => '网络错误！请重试'
                        ];
                    }
                } else {
                    return [
                        "success" => 'warning',
                        "msg" => $validate->getError()
                    ];
                }
            } else {
                return [
                    "success" => 'warning',
                    'msg' => '请填充数据'
                ];
            }
        } else {
            return [
                "success" => 'warning',
                'msg' => '网络错误！请重试'
            ];
        }
    }


//乙方导购人员树
    public
    function BPartyNameTreeP()
    {
        return $this->fetch();
    }

//乙方导购人员
    public
    function BPartyNameTree()
    {
        $data = Db::table('bx_guide_user')->where('nowState', 'not in', '2')->field('name,id')->select();
        echo json_encode($data);
    }

//乙方导购人员
    public
    function BPartyNameTreeJson()
    {
        $data = Db::table('bx_guide_user')->where('nowState', 'not in', '2')->field('name,id')->select();
        echo json_encode(['message' => 'ok', 'value' => $data, 'code' => '200', 'redirect' => '']);
    }

//劳动合同分析(没有合同的导购员)
    public
    function labourContractAnalysis()
    {
        //有合同的导购人员
        $id = Db::table('bx_guide_labour_contract')->column('BPartyName_id');
        $where = implode(',', $id);
        $data = Db::table('bx_guide_user')->alias('a')
            ->join('cg_net b', 'a.mainNet_id = b.id', 'LEFT')
            ->join('cg_market_zoning p', 'b.zoning = p.id', 'LEFT')//营销区
            ->join('cg_market_provice n', 'b.provice = n.id', 'LEFT')//营销省
            ->join('cg_market_city o', 'b.city = o.id', 'LEFT')//营销市
            ->join('cg_system e', 'b.system_id = e.id', 'LEFT')//系统表
            ->where("a.id not in ($where)")
            ->field("a.id,b.id wd_id,concat(o.title,'-',e.title,'\-',b.title) wd,a.name")
            ->select();
        $arr = '';
        foreach ($data as $key => $val) {
            $arr .= ',' . $val['id'];
        }
        $this->assign('data', $data);
        $this->assign('arr', substr($arr, 1));
        $this->assign('title', '缺少');
        return $this->fetch('ashippingguide/labourcontractanalysis');
    }

//劳动合同分析(不需要合同（临时）的导购员)
    public
    function labourContractAnalysisTmp()
    {
        //有合同的导购人员
        $id = Db::table('bx_guide_labour_contract')->column('BPartyName_id');
        $where = implode(',', $id);
        $data = Db::table('bx_guide_user')->alias('a')
            ->join('cg_net b', 'a.mainNet_id = b.id', 'LEFT')
            ->join('cg_market_zoning p', 'b.zoning = p.id', 'LEFT')//营销区
            ->join('cg_market_provice n', 'b.provice = n.id', 'LEFT')//营销省
            ->join('cg_market_city o', 'b.city = o.id', 'LEFT')//营销市
            ->join('cg_system e', 'b.system_id = e.id', 'LEFT')//系统表
            ->where("a.id not in ($where)")
            ->where('promoters', 1)
            ->field("a.id,b.id wd_id,concat(o.title,'-',e.title,'\-',b.title) wd,a.name")
            ->select();
        $arr = '';
        foreach ($data as $key => $val) {
            $arr .= ',' . $val['id'];
        }
        $this->assign('data', $data);
        $this->assign('arr', substr($arr, 1));
        $this->assign('title', '不需要');
        return $this->fetch('ashippingguide/labourcontractanalysis');
    }

//生成劳动合同
    public
    function createLabourContract()
    {
        $id = $this->request->get('id');
        if ($id) {
            $data = Db::table('bx_guide_user')->where("id in ($id)")
                ->field('id BPartyName_id,name BPartyName')->select();
            $date = date('Y-m-d');
            foreach ($data as $key => $val) {
                $data[$key]['indexes'] = 'A' . rand(0, 9999);
                $data[$key]['contractName'] = '自动创建-A' . rand(0, 9999);
                $data[$key]['APartyName'] = '自动创建-广州销路通软件公司';
                $data[$key]['signDate'] = $date;
                $data[$key]['endDate'] = date('Y-m-d', strtotime("$date +1 year"));
            }
            if (Db::table('bx_guide_labour_contract')->insertAll($data)) {
                return json([
                    'success' => true
                ]);
            } else {
                return json([
                    'success' => false
                ]);
            }
        }
    }

//导出缺失和不需要劳动合同
    public
    function exportLabourContractAnalysis()
    {
        $get = $this->request->get();
        if ($get['id']) {
            $user = Db::table('employee')->where('id', session('employee_id'))->value('em_name');
            $str = '注：本表单由销路通软件导出，导出时间：' . date('Y-m-d H:i:s') . '；导出人：' . $user;
            $str1 = $get['title'] . '劳动合同的职员';
//        $titles = ['姓名', '年龄', '性别', '身高'];
            // titles格式也可以如下
            $titles = [
                'No. ' => '序号',
                'wd' => '所在网点名称(城市-系统-网点)',
                'name' => '姓名',
            ];
            $where = $get['id'];
            Db::table('bx_guide_user')->query("set @i = 0");
            $data = Db::table('bx_guide_user')->alias('a')
                ->join('cg_net b', 'a.mainNet_id = b.id', 'LEFT')
                ->join('cg_market_zoning p', 'b.zoning = p.id', 'LEFT')//营销区
                ->join('cg_market_provice n', 'b.provice = n.id', 'LEFT')//营销省
                ->join('cg_market_city o', 'b.city = o.id', 'LEFT')//营销市
                ->join('cg_system e', 'b.system_id = e.id', 'LEFT')//系统表
                ->where("a.id not in ($where)")
                ->field("(@i:=@i+1) No,concat(o.title,'-',e.title,'\-',b.title) wd,a.name")
                ->select();
            $data[] = [
                'title' => $str1,
                'sub' => $str,
            ];
            $excel = new ExcelDownload();
            $excel->exec($data, $titles, $str1, ['sheet' => ['rowHeight' => 20]], 3);
        } else {
            echo "<script>top.sweetAlert('没有数据','','warning');history.go(-1);</script>";
        }
    }

//劳动合同查询
//导购劳动合同管理
    public
    function labourContractQuery()
    {
        //查询条件
        $where = $this->request->post();
        $this->assign('where', $where);
        $where = self::str($where);
        $page = empty($where['pages']) ? 1 : $where['pages'];
        $list = empty($where['limts']) ? 10 : $where['limts'];
        unset($where['pages']);
        unset($where['limts']);
        //总数量，总金额，总条数
        $count = Db::table('bx_guide_labour_contract')->alias('a')
            ->join('bx_guide_user b', 'a.BPartyName_id = b.id')
            ->join('cg_net c', 'b.mainNet_id = c.id', 'LEFT')
            ->where($where)
            ->count();
        $this->assign('count', $count);
        //分页
        $maxpage = ceil($count / $list);
        $page = $page < $maxpage ? $page : $maxpage;
        $page = $page > 1 ? $page : 1;
        $start = ($page - 1) * $list;
        $this->assign('page', $page);
        $this->assign('maxpage', $maxpage);
        $this->assign('limit', $list);
        //数据
        $data = Db::table('bx_guide_labour_contract')->alias('a')
            ->join('bx_guide_user b', 'a.BPartyName_id = b.id')
            ->join('cg_net c', 'b.mainNet_id = c.id', 'LEFT')
            ->field("a.id,a.indexes,a.BPartyName,(case 
            when b.postType = 0 then '全职'
            when b.postType = 1 then '兼职'
            when b.postType = 2 then '专职'
             end) postType,a.APartyName,b.mainNet_id,c.title mainNet,a.signDate,a.endDate,a.signNum,if(a.returnContract = 0,'x','√') returnContract,(case
            when b.nowState = 0 then '在职'
            when b.nowState = 1 then '使用'
            when b.nowState = 2 then '离职'
            end) state")
            ->where($where)->order('a.id', 'desc')
            ->limit($start, $list)
            ->select();
        $this->assign('data', $data);
        return $this->fetch();
    }

    //转正提醒
    public function reminding()
    {
        //查询条件
        $name = $this->request->post('name');
        $this->assign('name', $name);
        if ($name) {
            $id = Db::table('employee')->where('em_name', 'like', '%' . $name . '%')->value('id');
            if ($id) {
                $where = ['name' => ['like', '%' . $id . '%']];
                $data = Db::table('bx_guide_reminding')->where($where)->select();
            } else {
                $data = [];
            }
        } else {
            $data = Db::table('bx_guide_reminding')->select();
        }
        if ($data) {
            foreach ($data as $key => $val) {
                $name = [];
                $name = Db::table('employee')->where('id', 'in', $val['name'])->column('em_name');
                $data[$key]['name'] = implode(' , ', $name);
            }
        }
        $this->assign('data', $data);
        return $this->fetch();
    }

    //新增转正提醒
    public function addremindingp()
    {
        return $this->fetch();
    }

    public function addreminding()
    {
        $data = $this->request->post();
        $validate = new Validate([
            ['name', 'require', '提醒人必须'],
            ['type', 'require', '提醒方式必须'],
        ]);
        if ($validate->check($data)) {
            $data['type'] = implode(',', $data['type']);
            if (Db::table('bx_guide_reminding')->insert($data)) {
                return json([
                    "success" => true,
                    "msg" => '新增成功！'
                ]);
            } else {
                return json([
                    "success" => false,
                    "msg" => '网络错误！请重试'
                ]);
            }
        } else {
            return json([
                "success" => false,
                "msg" => $validate->getError()
            ]);
        }
    }

    //删除转正提醒
    public function delreminding()
    {
        $id = $this->request->get('id');
        if ($id) {
            if (Db::table('bx_guide_reminding')->where('id', $id)->delete()) {
                return json([
                    "success" => true,
                ]);
            } else {
                return json([
                    "success" => false,
                ]);
            }
        } else {
            return json([
                "success" => false,
            ]);
        }
    }

    //入职申请
    public function entryapply()
    {
        //查询条件
        $where = $this->request->post();
        $this->assign('where', $where);
        $where = self::str($where);
        $page = empty($where['pages']) ? 1 : $where['pages'];
        $list = empty($where['limts']) ? 10 : $where['limts'];
        unset($where['pages']);
        unset($where['limts']);
        //总数量，总金额，总条数
        $count = Db::table('bx_guide_apple_log')
            ->where('apple_name', 'bx_guide_user')
            ->where($where)
            ->count();
        $this->assign('count', $count);
        //分页
        $maxpage = ceil($count / $list);
        $page = $page < $maxpage ? $page : $maxpage;
        $page = $page > 1 ? $page : 1;
        $start = ($page - 1) * $list;
        $this->assign('page', $page);
        $this->assign('maxpage', $maxpage);
        $this->assign('limit', $list);
        //数据
        $data = Db::table('bx_guide_apple_log')
            ->where($where)
            ->where('apple_name', 'bx_guide_user')
            ->order('id', 'desc')
            ->limit($start, $list)
            ->select();
        $this->assign('data', $data);
        return $this->fetch();
    }

    //入职申请
    public function addentryapplep()
    {
        $user = Db::table('employee')->where('id', session('employee_id'))->value('em_name');
        $this->assign('user', $user);
        $salarylevel = Db::table('bx_guide_salarylevel')->field('id,salaryLevel')->select();
        $this->assign('salarylevel', $salarylevel);
        return $this->fetch();
    }

    //入职申请提交
    public function addentryapple()
    {
        $data = $this->request->post();
        if (!$data['entryDate']) $data['entryDate'] = NULL;
        if (!$data['justDate']) $data['justDate'] = NULL;
        if (!$data['birthDate']) $data['birthDate'] = NULL;
        if (!$data['quitDate']) $data['quitDate'] = NULL;
        $validate = new Validate([
            ['applicant', 'require', '申请人必须'],
            ['name', 'require', '姓名必须'],
            ['workNumber', 'require', '工牌号必须'],
            ['mainNet', 'require', '主网点必须'],
            ['postType', 'require', '岗位类型必须'],
            ['entryDate', 'require|date', '入职日期必须|日期格式'],
        ]);
        if ($validate->check($data)) {
            //人员userPhoto，工牌照片workPhoto，身份证IDPhoto，银行卡bankPhoto
            $userPhoto = request()->file('userPhoto');
            if (!empty($userPhoto)) {
//                // 移动到框架应用根目录/public/uploads/bx_guide 目录下
                $info1 = $userPhoto->validate(['ext' => 'png,jpg,jpeg,gif'])->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'bx_guide_user');
                if ($info1) {
                    // 成功上传后 获取上传信息
                    $data['userPhoto'] = $info1->getSaveName();
                } else {
                    // 上传失败获取错误信息
                    echo "<script>top.sweetAlert('" . $userPhoto->getError() . "','','success');history.go(-1);</script>";
                }
            }
            $workPhoto = request()->file('workPhoto');
            if (!empty($workPhoto)) {
//                // 移动到框架应用根目录/public/uploads/bx_guide 目录下
                $info2 = $workPhoto->validate(['ext' => 'png,jpg,jpeg,gif'])->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'bx_guide_user');
                if ($info2) {
                    // 成功上传后 获取上传信息
                    $data['workPhoto'] = $info2->getSaveName();
                } else {
                    // 上传失败获取错误信息
                    echo "<script>top.sweetAlert('" . $workPhoto->getError() . "','','success');history.go(-1);</script>";
                }
            }
            $IDPhoto = request()->file('IDPhoto');
            if (!empty($IDPhoto)) {
//                // 移动到框架应用根目录/public/uploads/bx_guide 目录下
                $info3 = $IDPhoto->validate(['ext' => 'png,jpg,jpeg,gif'])->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'bx_guide_user');
                if ($info3) {
                    // 成功上传后 获取上传信息
                    $data['IDPhoto'] = $info3->getSaveName();
                } else {
                    // 上传失败获取错误信息
                    echo "<script>top.sweetAlert('" . $IDPhoto->getError() . "','','success');history.go(-1);</script>";
                }
            }
            $bankPhoto = request()->file('bankPhoto');
            if (!empty($bankPhoto)) {
//                // 移动到框架应用根目录/public/uploads/bx_guide 目录下
                $info4 = $bankPhoto->validate(['ext' => 'png,jpg,jpeg,gif'])->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'bx_guide_user');
                if ($info4) {
                    // 成功上传后 获取上传信息
                    $data['bankPhoto'] = $info4->getSaveName();
                } else {
                    // 上传失败获取错误信息
                    echo "<script>top.sweetAlert('" . $bankPhoto->getError() . "','','success');history.go(-1);</script>";
                }
            }
            $uplaodify = $data['exampleInputFile'];
            unset($data['exampleInputFile']);
            if ($id = Db::table('bx_guide_user')->insertGetId($data)) {
                $BaseData = new Ashippingmanagement2();
                $BaseData->file($uplaodify, 'bx_guide_user', $id);
                unset($uplaodify);
                //申请日志
                $data['isdraft'] == 0 ? $isdraft = '草稿' : $isdraft = '已提交';
                $log = [
                    'no' => date('Ymd') . '00' . rand('0', '999'),
                    'theme' => $data['applicant'] . '的入职申请',
                    'state' => $isdraft,
                    'fillinDate' => $data['fillintime'],
                    'apple_id' => $id,
                    'apple_name' => 'bx_guide_user',
                ];
                Db::table('bx_guide_apple_log')->insert($log);
                $this->redirect('ashippingguide/entryapply');
            } else {
                echo "<script>top.sweetAlert('网络错误！请重试','','warning');</script>";
            }
        } else {
            echo "<script>top.sweetAlert('" . $validate->getError() . "','','warning');</script>";
        }

    }

    //异动申请
    public function accidentapply()
    {
        //查询条件
        $where = $this->request->post();
        $this->assign('where', $where);
        $where = self::str($where);
        $page = empty($where['pages']) ? 1 : $where['pages'];
        $list = empty($where['limts']) ? 10 : $where['limts'];
        unset($where['pages']);
        unset($where['limts']);
        //总数量，总金额，总条数
        $count = Db::table('bx_guide_apple_log')
            ->where('apple_name', 'bx_guide_accident')
            ->where($where)
            ->count();
        $this->assign('count', $count);
        //分页
        $maxpage = ceil($count / $list);
        $page = $page < $maxpage ? $page : $maxpage;
        $page = $page > 1 ? $page : 1;
        $start = ($page - 1) * $list;
        $this->assign('page', $page);
        $this->assign('maxpage', $maxpage);
        $this->assign('limit', $list);
        //数据
        $data = Db::table('bx_guide_apple_log')
            ->where($where)
            ->where('apple_name', 'bx_guide_accident')
            ->order('id', 'desc')
            ->limit($start, $list)
            ->select();
        $this->assign('data', $data);
        return $this->fetch();
    }

    //离职申请
    public function quitapply()
    {
        //查询条件
        $where = $this->request->post();
        $this->assign('where', $where);
        $where = self::str($where);
        $page = empty($where['pages']) ? 1 : $where['pages'];
        $list = empty($where['limts']) ? 10 : $where['limts'];
        unset($where['pages']);
        unset($where['limts']);
        //总数量，总金额，总条数
        $count = Db::table('bx_guide_apple_log')
            ->where('apple_name', 'bx_guide_quit')
            ->where($where)
            ->count();
        $this->assign('count', $count);
        //分页
        $maxpage = ceil($count / $list);
        $page = $page < $maxpage ? $page : $maxpage;
        $page = $page > 1 ? $page : 1;
        $start = ($page - 1) * $list;
        $this->assign('page', $page);
        $this->assign('maxpage', $maxpage);
        $this->assign('limit', $list);
        //数据
        $data = Db::table('bx_guide_apple_log')
            ->where($where)
            ->where('apple_name', 'bx_guide_quit')
            ->order('id', 'desc')
            ->limit($start, $list)
            ->select();
        $this->assign('data', $data);
        return $this->fetch();
    }

    //新增申请，0=异动，1=离职
    public function addapplyp()
    {
        $type = $this->request->get('type');
        $this->assign('type', $type);

        //查询条件
        $where = $this->request->post();
        $this->assign('where', $where);
        $where = self::str($where);
        $page = empty($where['pages']) ? 1 : $where['pages'];
        $list = empty($where['limts']) ? 10 : $where['limts'];
        unset($where['pages']);
        unset($where['limts']);
        //总数量，总金额，总条数
        $count = Db::table('bx_guide_user')->alias('a')
            ->join('cg_net b', 'a.mainNet_id = b.id')
            ->join('cg_market_zoning p', 'b.zoning = p.id', 'LEFT')//营销区
            ->join('cg_market_provice n', 'b.provice = n.id', 'LEFT')//营销省
            ->join('cg_market_city o', 'b.city = o.id', 'LEFT')//营销市
            ->join('cg_system e', 'b.system_id = e.id', 'LEFT')//系统表
            ->where($where)
            ->count();
        $this->assign('count', $count);
        //分页
        $maxpage = ceil($count / $list);
        $page = $page < $maxpage ? $page : $maxpage;
        $page = $page > 1 ? $page : 1;
        $start = ($page - 1) * $list;
        $this->assign('page', $page);
        $this->assign('maxpage', $maxpage);
        $this->assign('limit', $list);
        //数据
        $data = Db::table('bx_guide_user')->alias('a')
            ->join('cg_net b', 'a.mainNet_id = b.id')
            ->join('cg_market_zoning p', 'b.zoning = p.id', 'LEFT')//营销区
            ->join('cg_market_provice n', 'b.provice = n.id', 'LEFT')//营销省
            ->join('cg_market_city o', 'b.city = o.id', 'LEFT')//营销市
            ->join('cg_system e', 'b.system_id = e.id', 'LEFT')//系统表
            ->field("a.name,concat(o.title,'-',e.title,'\-',b.title) wd,
            a.phone,a.IDNo,(case
            when a.nowState = 0 then '在职'
            when a.nowState = 1 then '使用'
            when a.nowState = 2 then '离职'
            end) state,a.id")
            ->where($where)->order('a.id', 'desc')
            ->limit($start, $list)
            ->select();
        $this->assign('data', $data);
        return $this->fetch();
    }

    //异动修改导购人员页面
    public
    function editGuide2()
    {
        $id = $this->request->get('id');
        if ($id) {
            $data = Db::table('bx_guide_user')->where('id', $id)->find();
            $this->assign('data', $data);
            //附件
            $BaseData = new Ashippingmanagement2();
            $uploadify = $BaseData->fileSelect($id, 'bx_guide_user');
            $this->assign('uploadify', $uploadify);
            return $this->fetch();
        } else {
            echo '主键缺失！';
        }
    }

    //异动修改导购人员
    public
    function editguideform2()
    {
        $data = $this->request->post();
        if (!$data['entryDate']) $data['entryDate'] = NULL;
        if (!$data['justDate']) $data['justDate'] = NULL;
        if (!$data['birthDate']) $data['birthDate'] = NULL;
        if ($data['id']) {
            $validate = new Validate([
                ['name', 'require', '姓名必须'],
                ['workNumber', 'require', '工牌号必须'],
                ['mainNet', 'require', '主网点必须'],
                ['postType', 'require', '岗位类型必须'],
                ['entryDate', 'require|date', '入职日期必须|日期格式'],
            ]);
            if ($validate->check($data)) {
                //人员userPhoto，工牌照片workPhoto，身份证IDPhoto，银行卡bankPhoto
                $userPhoto = request()->file('userPhoto');
                if (!empty($userPhoto)) {
//                // 移动到框架应用根目录/public/uploads/bx_guide 目录下
                    $info1 = $userPhoto->validate(['ext' => 'png,jpg,jpeg,gif'])->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'bx_guide_user');
                    if ($info1) {
                        // 成功上传后 获取上传信息
                        $data['userPhoto'] = $info1->getSaveName();
                    } else {
                        // 上传失败获取错误信息
                        echo "<script>top.sweetAlert('" . $userPhoto->getError() . "','','success');history.go(-1);</script>";
                    }
                }
                $workPhoto = request()->file('workPhoto');
                if (!empty($workPhoto)) {
//                // 移动到框架应用根目录/public/uploads/bx_guide 目录下
                    $info2 = $workPhoto->validate(['ext' => 'png,jpg,jpeg,gif'])->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'bx_guide_user');
                    if ($info2) {
                        // 成功上传后 获取上传信息
                        $data['workPhoto'] = $info2->getSaveName();
                    } else {
                        // 上传失败获取错误信息
                        echo "<script>top.sweetAlert('" . $workPhoto->getError() . "','','success');history.go(-1);</script>";
                    }
                }
                $IDPhoto = request()->file('IDPhoto');
                if (!empty($IDPhoto)) {
//                // 移动到框架应用根目录/public/uploads/bx_guide 目录下
                    $info3 = $IDPhoto->validate(['ext' => 'png,jpg,jpeg,gif'])->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'bx_guide_user');
                    if ($info3) {
                        // 成功上传后 获取上传信息
                        $data['IDPhoto'] = $info3->getSaveName();
                    } else {
                        // 上传失败获取错误信息
                        echo "<script>top.sweetAlert('" . $IDPhoto->getError() . "','','success');history.go(-1);</script>";
                    }
                }
                $bankPhoto = request()->file('bankPhoto');
                if (!empty($bankPhoto)) {
//                // 移动到框架应用根目录/public/uploads/bx_guide 目录下
                    $info4 = $bankPhoto->validate(['ext' => 'png,jpg,jpeg,gif'])->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'bx_guide_user');
                    if ($info4) {
                        // 成功上传后 获取上传信息
                        $data['bankPhoto'] = $info4->getSaveName();
                    } else {
                        // 上传失败获取错误信息
                        echo "<script>top.sweetAlert('" . $bankPhoto->getError() . "','','success');history.go(-1);</script>";
                    }
                }
                $BaseData = new Ashippingmanagement2();
                $BaseData->file($data['exampleInputFile'], 'bx_guide_user', $data['id']);
                unset($data['exampleInputFile']);
                //异动修改字段比较
                self::compare('bx_guide_user', $data);
                Db::table('bx_guide_user')->where('id', $data['id'])->update($data);
                $this->redirect('ashippingguide/accidentapply');
            } else {
                echo "<script>top.sweetAlert('" . $validate->getError() . "','','warning');history.go(-1);</script>";
            }
        } else {
            echo '主键错误';
        }

    }


    //离职新增
    public function quitguidep()
    {
        //导购人员id
        $id = $this->request->get('id');
        if ($id) {
            $user = Db::table('employee')->where('id', session('employee_id'))->value('em_name');
            $this->assign('user', $user);
            //人事类型
            $tingType = Db::table('bx_guide_thingtype')->alias('a')
                ->join('bx_guide_user c', 'a.user_id = c.id')
                ->join('cg_net b', 'c.mainNet_id = b.id', 'LEFT')
                ->join('cg_market_zoning p', 'b.zoning = p.id', 'LEFT')//营销区
                ->join('cg_market_provice n', 'b.provice = n.id', 'LEFT')//营销省
                ->join('cg_market_city o', 'b.city = o.id', 'LEFT')//营销市
                ->join('cg_system e', 'b.system_id = e.id', 'LEFT')//系统表
                ->join('bx_guide_salaryLevel d', 'c.salarylevel_id = d.id', 'LEFT')//薪资级别
                ->field("a.tingType,a.okDate,a.reason,concat(o.title,'-',e.title,'\-',b.title) wd,(case
            when c.postType = 0 then '全职'
            when c.postType = 1 then '兼职'
            when c.postType = 2 then '专职'
            end) postType,d.salaryLevel")
                ->where('a.user_id', $id)->select();
            $this->assign('tingType', $tingType);
            //信息
            $data = Db::table('bx_guide_user')->alias('a')
                ->join('bx_guide_quit c', 'a.id = c.user_id', 'LEFT')
                ->join('cg_net b', 'a.mainNet_id = b.id', 'LEFT')
                ->join('cg_jxs d', 'b.jxs = d.id', 'LEFT')
                ->join('cg_market_zoning p', 'b.zoning = p.id', 'LEFT')//营销区
                ->join('cg_market_provice n', 'b.provice = n.id', 'LEFT')//营销省
                ->join('cg_market_city o', 'b.city = o.id', 'LEFT')//营销市
                ->join('cg_system e', 'b.system_id = e.id', 'LEFT')//系统表
                ->field("a.*,c.quitDes,b.id wd_id,concat(o.title,'-',e.title,'\-',b.title) wd,
                b.sn wd_no,p.title yq,n.title ys,o.title yshi,e.title xt,d.title jxs,c.id quit_id")
                ->where('a.id', $id)->find();
            $str = ['在职', '试用', '离职'];
            $data['nowState'] = $str[$data['nowState']];
            $str1 = ['全职', '兼职', '专职'];
            $data['postType'] = $str1[$data['postType']];
            $this->assign('data', $data);
            //附件
            $file = new Ashippingmanagement2();
            $uploadify = $file->fileSelect($id, 'bx_guide_user');
            $this->assign('uploadify', $uploadify);
            return $this->fetch();
        } else {
            echo '主键缺失';
        }
    }

    //离职修改和新增
    public function quitguide()
    {
        $data = $this->request->post();
        if ($data['id']) {
            $quit = [
                'user_id' => $data['id'],
                'quitDes' => $data['quitDes'],
            ];
            $data['isdraft'] == 0 ? $isdraft = '草稿' : $isdraft = '已提交';
            $log = [
                'no' => date('Ymd') . '00' . rand('0', '999'),
                'theme' => $data['name'] . '的离职申请',
                'state' => $isdraft,
                'fillinDate' => $data['fillintime'],
                'apple_id' => $data['id'],
                'apple_name' => 'bx_guide_quit',
            ];
            //有值更新
            if ($data['quit_id']) {
                Db::table('bx_guide_quit')->where('id', $data['quit_id'])->update($quit);
            } else {
                //没值新增
                Db::table('bx_guide_quit')->insert($quit);
                //人事类型
                $thingType = [
                    'user_id' => $data['id'],
                    'tingType' => '离职',
                    'okDate' => date('Y-m-d H:i:s'),
                    'reason' => $data['quitDes'],
                ];
                //人事类型
                Db::table('bx_guide_thingtype')->insert($thingType);
                Db::table('bx_guide_apple_log')->insert($log);
            }

            //附件
            $BaseData = new Ashippingmanagement2();
            $BaseData->file($data['exampleInputFile'], 'bx_guide_user', $data['id']);
            unset($data['exampleInputFile']);
            unset($data['quitDes']);
            unset($data['quit_id']);
            unset($data['log_id']);
            Db::table('bx_guide_user')->where('id', $data['id'])->update($data);
            $this->redirect('ashippingguide/quitapply');
        } else {
            echo '主键缺失！';
        }
    }

    //删除离职申请
    public function delquitapply()
    {
        //bx_guide_apple_log主键
        $id = $this->request->get('id');
        if ($id) {
            if (Db::table('bx_guide_apple_log')->where(['apple_id' => $id, 'apple_name' => 'bx_guide_quit'])->delete()) {
                if (Db::table('bx_guide_quit')->where('user_id', $id)->delete()) {
                    return json([
                        'success' => true,
                    ]);
                }
            }
        } else {
            return json([
                'success' => false,
                'msg' => '非法请求！'
            ]);
        }
    }


    /**
     *  异动比较字段
     * @param $table //表名，必须
     * @param $data //表单，携带id
     */
    private function compare($table, $data)
    {
        //汉字对照
        $chinesField = [
            'id' => '主键',
            'name' => '导购姓名',
            'workNumber' => '导购工牌号',
            'mainNet' => '导购所属主网点',
            'mainNet_id' => '导购所属主网点',
            'otherNet' => '导购更多所属网点',
            'otherNet_id' => '导购更多所属网点',
            'postType' => '岗位类型',
            'entryDate' => '入职时间',
            'justDate' => '转正时间',
            'manageMoney' => '导购管理费',
            'safeMoney' => '导购保险',
            'otherMoney' => '导购杂费',
            'otherSubsidyMoney' => '导购其他补贴',
            'IDNo' => '导购身份证号',
            'nation' => '导购民族',
            'signContract' => '是否签订合同',
            'sex' => '导购性别',
            'fanPin' => '是否允许返聘',
            'phone' => '导购手机号',
            'weixin' => '导购微信号',
            'email' => '导购邮箱',
            'promoters' => '导购促销员类型',
            'birthDate' => '导购出生日期',
            'pinpai' => '导购所属品牌',
            'pinpai_id' => '导购所属品牌',
            'pinlei' => '导购所属品类',
            'pinlei_id' => '导购所属品类',
            'recruitmentChannels' => '导购招聘渠道',
            'guideGrade' => '导购等级',
            'referee' => '招聘推荐人及部门',
            'referee_id' => '招聘推荐人及部门',
            'urgentLinkman' => '导购紧急联系人',
            'urgentTel' => '导购紧急联系人电话',
            'guideRelationship' => '导购与导购员关系',
            'openingBank' => '导购开户行',
            'bankAccount' => '导购开户银行',
            'livingProvince' => '现居住地址省',
            'livingCity' => '现居住地址市',
            'livingCounty' => '现居住地址区',
            'livingAddress' => '现居住地址',
            'houseProvince' => '户籍地址省',
            'houseCity' => '户籍地址市',
            'houseCounty' => '户籍地址区',
            'houseAddress' => '户籍地址',
            'houseType' => '户口性质',
            'nowState' => '目前状态',
            'quitType' => '离职类型',
            'des' => '导购管理费',
            'userPhoto' => '一寸免冠照片',
            'workPhoto' => '工牌照片',
            'IDPhoto' => '身份证照片',
            'bankPhoto' => '银行卡照片',
        ];
        //导购岗位（角色role
        //获取要比较的字段
        $field = array_keys($data);
        //拼接，查数据库
        $tmpField = implode(',', $field);
        $oldData = Db::table($table)->field($tmpField)->where('id', $data['id'])->find();
        $tmp = [];
        $no = date('Ymd') . '00' . rand('0', '999');
        foreach ($data as $key => $val) {
            if (strcmp($data[$key], $oldData[$key])) {
                $tmp[] = [
                    'no' => $no,
                    'okDate' => date('Y-m-d H:i:s'),
                    'field' => $chinesField[$key],
                    'oldDes' => $oldData[$key],
                    'newDes' => $data[$key],
                    'user_id' => $data['id'],
                ];
            }
        }
        if ($tmp) {
            //人事类型
            $thingType = [
                'user_id' => $data['id'],
                'tingType' => '异动',
                'okDate' => date('Y-m-d H:i:s'),
                'reason' => '根据编号【' . $no . '】，修改档案',
            ];
            //异动
            Db::table('bx_guide_accident')->insertAll($tmp);
            //人事类型
            Db::table('bx_guide_thingtype')->insert($thingType);
            $log = [
                'no' => $no,
                'theme' => $data['name'] . '的入职申请',
                'state' => '已更改',
                'fillinDate' => date('Y-m-d H:i:s'),
                'apple_id' => $data['id'],
                'apple_name' => 'bx_guide_accident',
            ];
            Db::table('bx_guide_apple_log')->insert($log);
            //导购人事日志
            $usetLog = [
                'user_id' => session('employee_id'),//当前系统人id
                'time' => date('Y-m-d H:i:s'),
                'logType' => '导购人事日志',
                'content' => '根据编号【' . $no . '】，修改了导购员' . $data['name'] . '的档案',
            ];
            Db::table('bx_guide_user_log')->insert($usetLog);
        }
        return true;
    }

    /**
     *  修改字段比较字段
     * @param $table //表名，必须
     * @param $data //表单，携带id
     */
    private function compare2($table, $data)
    {
        //汉字对照
        $chinesField = [
            'id' => '主键',
            'name' => '导购姓名',
            'workNumber' => '导购工牌号',
            'mainNet' => '导购所属主网点',
            'mainNet_id' => '导购所属主网点',
            'otherNet' => '导购更多所属网点',
            'otherNet_id' => '导购更多所属网点',
            'postType' => '岗位类型',
            'entryDate' => '入职时间',
            'justDate' => '转正时间',
            'manageMoney' => '导购管理费',
            'safeMoney' => '导购保险',
            'otherMoney' => '导购杂费',
            'otherSubsidyMoney' => '导购其他补贴',
            'IDNo' => '导购身份证号',
            'nation' => '导购民族',
            'signContract' => '是否签订合同',
            'sex' => '导购性别',
            'fanPin' => '是否允许返聘',
            'phone' => '导购手机号',
            'weixin' => '导购微信号',
            'email' => '导购邮箱',
            'promoters' => '导购促销员类型',
            'birthDate' => '导购出生日期',
            'pinpai' => '导购所属品牌',
            'pinpai_id' => '导购所属品牌',
            'pinlei' => '导购所属品类',
            'pinlei_id' => '导购所属品类',
            'recruitmentChannels' => '导购招聘渠道',
            'guideGrade' => '导购等级',
            'referee' => '招聘推荐人及部门',
            'referee_id' => '招聘推荐人及部门',
            'urgentLinkman' => '导购紧急联系人',
            'urgentTel' => '导购紧急联系人电话',
            'guideRelationship' => '导购与导购员关系',
            'openingBank' => '导购开户行',
            'bankAccount' => '导购开户银行',
            'livingProvince' => '现居住地址省',
            'livingCity' => '现居住地址市',
            'livingCounty' => '现居住地址区',
            'livingAddress' => '现居住地址',
            'houseProvince' => '户籍地址省',
            'houseCity' => '户籍地址市',
            'houseCounty' => '户籍地址区',
            'houseAddress' => '户籍地址',
            'houseType' => '户口性质',
            'nowState' => '目前状态',
            'quitType' => '离职类型',
            'des' => '导购管理费',
            'userPhoto' => '一寸免冠照片',
            'workPhoto' => '工牌照片',
            'IDPhoto' => '身份证照片',
            'bankPhoto' => '银行卡照片',
        ];
        //导购岗位（角色role
        //获取要比较的字段
        $field = array_keys($data);
        //拼接，查数据库
        $tmpField = implode(',', $field);
        $oldData = Db::table($table)->field($tmpField)->where('id', $data['id'])->find();
        $tmp = [];
        $no = date('Ymd') . '00' . rand('0', '999');
        foreach ($data as $key => $val) {
            if (strcmp($data[$key], $oldData[$key])) {
                $tmp[] = [
                    'no' => $no,
                    'okDate' => date('Y-m-d H:i:s'),
                    'field' => $chinesField[$key],
                    'oldDes' => $oldData[$key],
                    'newDes' => $data[$key],
                    'user_id' => $data['id'],
                ];
            }
        }
        if ($tmp) {
            //人事类型
            $thingType = [
                'user_id' => $data['id'],
                'tingType' => '异动',
                'okDate' => date('Y-m-d H:i:s'),
                'reason' => '修改档案',
            ];
            //异动
            Db::table('bx_guide_accident')->insertAll($tmp);
            //人事类型
            Db::table('bx_guide_thingtype')->insert($thingType);
            $log = [
                'no' => $no,
                'theme' => $data['name'] . '的入职申请',
                'state' => '已更改',
                'fillinDate' => date('Y-m-d H:i:s'),
                'apple_id' => $data['id'],
                'apple_name' => 'bx_guide_accident',
            ];
            Db::table('bx_guide_apple_log')->insert($log);
            //导购人事日志
            $usetLog = [
                'user_id' => session('employee_id'),//当前系统人id
                'time' => date('Y-m-d H:i:s'),
                'logType' => '导购人事日志',
                'content' => '修改了导购员' . $data['name'] . '的档案',
            ];
            Db::table('bx_guide_user_log')->insert($usetLog);
        }
        return true;
    }


    //所属导购入职查询
    public function queryentry()
    {
        //查询条件
        $where = $this->request->post();
        $this->assign('where', $where);
        $where = self::str1($where);
        $page = empty($where['pages']) ? 1 : $where['pages'];
        $list = empty($where['limts']) ? 10 : $where['limts'];
        unset($where['pages']);
        unset($where['limts']);
        //总数量，总金额，总条数
        $count = Db::table('bx_guide_apple_log')->alias('a')
            ->join('bx_guide_user b', 'a.apple_id = b.id')
            ->join('cg_net c', 'b.mainNet_id = c.id')
            ->join('cg_market_zoning p', 'c.zoning = p.id', 'LEFT')//营销区
            ->join('cg_market_provice n', 'c.provice = n.id', 'LEFT')//营销省
            ->join('cg_market_city o', 'c.city = o.id', 'LEFT')//营销市
            ->join('cg_system e', 'c.system_id = e.id', 'LEFT')//系统表
            ->where($where)
            ->where('apple_name', 'bx_guide_user')
            ->count();
        $this->assign('count', $count);
        //分页
        $maxpage = ceil($count / $list);
        $page = $page < $maxpage ? $page : $maxpage;
        $page = $page > 1 ? $page : 1;
        $start = ($page - 1) * $list;
        $this->assign('page', $page);
        $this->assign('maxpage', $maxpage);
        $this->assign('limit', $list);
        //数据
        $data = Db::table('bx_guide_apple_log')->alias('a')
            ->join('bx_guide_user b', 'a.apple_id = b.id')
            ->join('cg_net c', 'b.mainNet_id = c.id')
            ->join('cg_market_zoning p', 'c.zoning = p.id', 'LEFT')//营销区
            ->join('cg_market_provice n', 'c.provice = n.id', 'LEFT')//营销省
            ->join('cg_market_city o', 'c.city = o.id', 'LEFT')//营销市
            ->join('cg_system e', 'c.system_id = e.id', 'LEFT')//系统表
            ->field("a.id,a.no,a.theme,a.state,p.title yq,n.title ys,o.title yshi,e.title xt,c.title wd,
            a.apple_id user_id,b.name,b.entryDate,b.applicant")
            ->where($where)->order('a.id', 'desc')
            ->where('apple_name', 'bx_guide_user')
            ->limit($start, $list)
            ->select();
        $this->assign('data', $data);
        return $this->fetch();
    }

    //替换_
    public function str1($where)
    {
        $tmp = [];
        $like = [
            'a_no' => ['like', '%val%'],
            'a_theme' => ['like', '%val%'],
            'p_title' => ['like', '%val%'],
            'n_title' => ['like', '%val%'],
            'o_title' => ['like', '%val%'],
            'e_title' => ['like', '%val%'],
            'c_title' => ['like', '%val%'],
            'd_title' => ['like', '%val%'],
            'd_sn' => ['like', '%val%'],
            'c_sn' => ['like', '%val%'],
            'b_applicant' => ['like', '%val%'],
            'a_state' => ['like', '%val%'],
            'b_name' => ['like', '%val%'],
            'd_field' => ['like', '%val%'],
            'b_em_name' => ['like', '%val%'],
            'd_de_name' => ['like', '%val%'],
            'a_content' => ['like', '%val%'],
            'a_name' => ['like', '%val%'],
            'ny' => ['like', '%val%'],
            'a_year' => ['like', '%val%'],
            'a_ny' => ['like', '%val%'],
            'pages' => 'val',
            'limts' => 'val',

        ];
        foreach ($where as $key => $val) {
            if (!empty($val)) {
                if (isset($where['entryDate']) && isset($where['end'])) {
                    if ($where['entryDate'] && $where['end']) {
                        $tmp['b.entryDate'] = ['between', [$where['entryDate'], $where['end']]];
                    } else if ($where['entryDate']) {
                        $tmp['b.entryDate'] = ['>=', $where['entryDate']];
                    } else if ($where['end']) {
                        $tmp['b.entryDate'] = ['<=', $where['end']];
                    }
                }
                if (isset($where['okDate']) && isset($where['end1'])) {
                    if ($where['okDate'] && $where['end1']) {
                        $tmp['d.okDate'] = ['between', [$where['okDate'], $where['end1']]];
                    } else if ($where['okDate']) {
                        $tmp['d.okDate'] = ['>=', $where['okDate']];
                    } else if ($where['end1']) {
                        $tmp['d.okDate'] = ['<=', $where['end1']];
                    }
                }
                if (isset($where['quitDate']) && isset($where['end'])) {
                    if ($where['quitDate'] && $where['end']) {
                        $tmp['b.quitDate'] = ['between', [$where['quitDate'], $where['end']]];
                    } else if ($where['quitDate']) {
                        $tmp['b.quitDate'] = ['>=', $where['quitDate']];
                    } else if ($where['end']) {
                        $tmp['b.quitDate'] = ['<=', $where['end']];
                    }
                }
                if (isset($where['time']) && isset($where['end'])) {
                    if ($where['time'] && $where['end']) {
                        $tmp['a.time'] = ['between', [$where['time'], $where['end']]];
                    } else if ($where['time']) {
                        $tmp['a.time'] = ['>=', $where['time']];
                    } else if ($where['end']) {
                        $tmp['a.time'] = ['<=', $where['end']];
                    }
                }
                foreach ($like as $k => $v) {
                    if ($key == $k) {
                        $tmp[preg_replace('/\_/', '.', $key, 1)] = str_replace('val', $val, $v);
                    }
                }

            }
            unset($tmp['items']);

        }
        return $tmp;
    }

    //导出所属导购入职查询
    public
    function exportentry()
    {
        $user = Db::table('employee')->where('id', session('employee_id'))->value('em_name');
        $str = '注：本表单由销路通软件导出，导出时间：' . date('Y-m-d H:i:s') . '；导出人：' . $user;
        $str1 = '所属导购入职查询';
//        $titles = ['姓名', '年龄', '性别', '身高'];
        // titles格式也可以如下
        $titles = [
            'no' => '编号',
            'theme' => '主题',
            'state' => '状态',
            'yq' => '分区名称',
            'ys' => '省份名称',
            'yshi' => '城市名称',
            'xt' => '系统名称',
            'wd' => '网点名称',
            'name' => '导购姓名',
            'entryDate' => '入职时间',
            'applicant' => '申请人',
        ];
        $data = Db::table('bx_guide_apple_log')->alias('a')
            ->join('bx_guide_user b', 'a.apple_id = b.id')
            ->join('cg_net c', 'b.mainNet_id = c.id')
            ->join('cg_market_zoning p', 'c.zoning = p.id', 'LEFT')//营销区
            ->join('cg_market_provice n', 'c.provice = n.id', 'LEFT')//营销省
            ->join('cg_market_city o', 'c.city = o.id', 'LEFT')//营销市
            ->join('cg_system e', 'c.system_id = e.id', 'LEFT')//系统表
            ->field("a.no,a.theme,a.state,p.title yq,n.title ys,o.title yshi,e.title xt,c.title wd,
           b.name,b.entryDate,b.applicant")
            ->where('apple_name', 'bx_guide_user')
            ->select();
        $data[] = [
            'title' => $str1,
            'sub' => $str,
        ];
        $excel = new ExcelDownload();
        $excel->exec($data, $titles, '所属导购入职查询', ['sheet' => ['rowHeight' => 20]], 3);
    }


    //所属导购查询异动
    public function queryaccident()
    {
        //查询条件
        $where = $this->request->post();
        $this->assign('where', $where);
        $where = self::str1($where);
        $page = empty($where['pages']) ? 1 : $where['pages'];
        $list = empty($where['limts']) ? 10 : $where['limts'];
        unset($where['pages']);
        unset($where['limts']);
        //总数量，总金额，总条数
        $count = Db::table('bx_guide_apple_log')->alias('a')
            ->join('bx_guide_user b', 'a.apple_id = b.id')
            ->join('cg_net c', 'b.mainNet_id = c.id')
            ->join('cg_market_zoning p', 'c.zoning = p.id', 'LEFT')//营销区
            ->join('cg_market_provice n', 'c.provice = n.id', 'LEFT')//营销省
            ->join('cg_market_city o', 'c.city = o.id', 'LEFT')//营销市
            ->join('cg_system e', 'c.system_id = e.id', 'LEFT')//系统表
            ->join('bx_guide_accident d', 'a.apple_id = d.user_id')//导购异动记录表
            ->where($where)
            ->where('apple_name', 'bx_guide_accident')
            ->count();
        $this->assign('count', $count);
        //分页
        $maxpage = ceil($count / $list);
        $page = $page < $maxpage ? $page : $maxpage;
        $page = $page > 1 ? $page : 1;
        $start = ($page - 1) * $list;
        $this->assign('page', $page);
        $this->assign('maxpage', $maxpage);
        $this->assign('limit', $list);
        //数据
        $data = Db::table('bx_guide_apple_log')->alias('a')
            ->join('bx_guide_user b', 'a.apple_id = b.id')
            ->join('cg_net c', 'b.mainNet_id = c.id')
            ->join('cg_market_zoning p', 'c.zoning = p.id', 'LEFT')//营销区
            ->join('cg_market_provice n', 'c.provice = n.id', 'LEFT')//营销省
            ->join('cg_market_city o', 'c.city = o.id', 'LEFT')//营销市
            ->join('cg_system e', 'c.system_id = e.id', 'LEFT')//系统表
            ->join('bx_guide_accident d', 'a.apple_id = d.user_id')//导购异动记录表
            ->field("a.id,a.no,a.theme,a.state,p.title yq,n.title ys,o.title yshi,e.title xt,c.title wd,
            a.apple_id user_id,b.name,b.entryDate,b.applicant,d.field,d.okDate,d.oldDes,d.newDes")
            ->where($where)->order('a.id', 'desc')
            ->where('apple_name', 'bx_guide_accident')
            ->limit($start, $list)
            ->select();
        foreach ($data as $key => $val) {
            $data[$key]['gw1'] = '';
            $data[$key]['gw2'] = '';
            $data[$key]['dj1'] = '';
            $data[$key]['dj2'] = '';
            $data[$key]['qt'] = '';
            if ($val['field'] == '导购等级') {
                $data[$key]['dj1'] = $data[$key]['oldDes'];
                $data[$key]['dj2'] = $data[$key]['newDes'];
            } else if ($val['field'] == '导购岗位') {
                $data[$key]['gw1'] = $data[$key]['oldDes'];
                $data[$key]['gw2'] = $data[$key]['newDes'];
            } else {
                $data[$key]['qt'] = $data[$key]['field'] . '<br>异动前：' . $data[$key]['oldDes'] . '<br>异动后：' . $data[$key]['newDes'];
            }
            unset($data[$key]['field']);
            unset($data[$key]['oldDes']);
            unset($data[$key]['newDes']);
        }
        //异动类型
        $type = Db::table('bx_guide_accident')->column('field');
        $this->assign('type', array_unique($type));
        $this->assign('data', $data);
        return $this->fetch();
    }

    //导出所属导购异动查询
    public function exportaccident()
    {
        $user = Db::table('employee')->where('id', session('employee_id'))->value('em_name');
        $str = '注：本表单由销路通软件导出，导出时间：' . date('Y-m-d H:i:s') . '；导出人：' . $user;
        $str1 = '所属导购异动查询';
//        $titles = ['姓名', '年龄', '性别', '身高'];
        // titles格式也可以如下
        $titles = [
            'no' => '编号',
            'theme' => '主题',
            'state' => '状态',
            'yq' => '分区名称',
            'ys' => '省份名称',
            'yshi' => '城市名称',
            'xt' => '系统名称',
            'wd' => '网点名称',
            'name' => '导购姓名',
            'entryDate' => '入职时间',
            'applicant' => '申请人',
            'okDate' => '异动生效日期',
            'gw1' => '异动前岗位',
            'gw2' => '异动后岗位',
            'dj1' => '异动前等级',
            'dj2' => '异动后等级',
            'qt' => '其他启动内容备注',
        ];
        $data = Db::table('bx_guide_apple_log')->alias('a')
            ->join('bx_guide_user b', 'a.apple_id = b.id')
            ->join('cg_net c', 'b.mainNet_id = c.id')
            ->join('cg_market_zoning p', 'c.zoning = p.id', 'LEFT')//营销区
            ->join('cg_market_provice n', 'c.provice = n.id', 'LEFT')//营销省
            ->join('cg_market_city o', 'c.city = o.id', 'LEFT')//营销市
            ->join('cg_system e', 'c.system_id = e.id', 'LEFT')//系统表
            ->join('bx_guide_accident d', 'a.apple_id = d.user_id')//导购异动记录表
            ->field("a.no,a.theme,a.state,p.title yq,n.title ys,o.title yshi,e.title xt,c.title wd,
           b.name,b.entryDate,b.applicant,d.field,d.okDate,d.oldDes,d.newDes")
            ->where('apple_name', 'bx_guide_accident')
            ->select();
        foreach ($data as $key => $val) {
            $data[$key]['gw1'] = '';
            $data[$key]['gw2'] = '';
            $data[$key]['dj1'] = '';
            $data[$key]['dj2'] = '';
            $data[$key]['qt'] = '';
            if ($val['field'] == '导购等级') {
                $data[$key]['dj1'] = $data[$key]['oldDes'];
                $data[$key]['dj2'] = $data[$key]['newDes'];
            } else if ($val['field'] == '导购岗位') {
                $data[$key]['gw1'] = $data[$key]['oldDes'];
                $data[$key]['gw2'] = $data[$key]['newDes'];
            } else {
                $data[$key]['qt'] = $data[$key]['field'] . '<br>异动前：' . $data[$key]['oldDes'] . '<br>异动后：' . $data[$key]['newDes'];
            }
            unset($data[$key]['field']);
            unset($data[$key]['oldDes']);
            unset($data[$key]['newDes']);
        }
        $data[] = [
            'title' => $str1,
            'sub' => $str,
        ];
        $excel = new ExcelDownload();
        $excel->exec($data, $titles, '所属导购异动查询', ['sheet' => ['rowHeight' => 20]], 3);
    }


    //所属导购离职查询
    public function queryquit()
    {
        //查询条件
        $where = $this->request->post();
        $this->assign('where', $where);
        $where = self::str1($where);
        $page = empty($where['pages']) ? 1 : $where['pages'];
        $list = empty($where['limts']) ? 10 : $where['limts'];
        unset($where['pages']);
        unset($where['limts']);
        //总数量，总金额，总条数
        $count = Db::table('bx_guide_apple_log')->alias('a')
            ->join('bx_guide_user b', 'a.apple_id = b.id')
            ->join('cg_net c', 'b.mainNet_id = c.id')
            ->join('cg_market_zoning p', 'c.zoning = p.id', 'LEFT')//营销区
            ->join('cg_market_provice n', 'c.provice = n.id', 'LEFT')//营销省
            ->join('cg_market_city o', 'c.city = o.id', 'LEFT')//营销市
            ->join('cg_system e', 'c.system_id = e.id', 'LEFT')//系统表
            ->where($where)
            ->where('apple_name', 'bx_guide_quit')
            ->count();
        $this->assign('count', $count);
        //分页
        $maxpage = ceil($count / $list);
        $page = $page < $maxpage ? $page : $maxpage;
        $page = $page > 1 ? $page : 1;
        $start = ($page - 1) * $list;
        $this->assign('page', $page);
        $this->assign('maxpage', $maxpage);
        $this->assign('limit', $list);
        //数据
        $data = Db::table('bx_guide_apple_log')->alias('a')
            ->join('bx_guide_user b', 'a.apple_id = b.id')
            ->join('cg_net c', 'b.mainNet_id = c.id')
            ->join('cg_market_zoning p', 'c.zoning = p.id', 'LEFT')//营销区
            ->join('cg_market_provice n', 'c.provice = n.id', 'LEFT')//营销省
            ->join('cg_market_city o', 'c.city = o.id', 'LEFT')//营销市
            ->join('cg_system e', 'c.system_id = e.id', 'LEFT')//系统表
            ->field("a.id,a.no,a.theme,a.state,p.title yq,n.title ys,o.title yshi,e.title xt,c.title wd,
            a.apple_id user_id,b.name,b.quitDate,b.applicant")
            ->where($where)->order('a.id', 'desc')
            ->where('apple_name', 'bx_guide_quit')
            ->limit($start, $list)
            ->select();
        $this->assign('data', $data);
        return $this->fetch();
    }

    //导出所属导购离职查询
    public
    function exportquit()
    {
        $user = Db::table('employee')->where('id', session('employee_id'))->value('em_name');
        $str = '注：本表单由销路通软件导出，导出时间：' . date('Y-m-d H:i:s') . '；导出人：' . $user;
        $str1 = '所属导购离职查询';
//        $titles = ['姓名', '年龄', '性别', '身高'];
        // titles格式也可以如下
        $titles = [
            'no' => '编号',
            'theme' => '主题',
            'state' => '状态',
            'yq' => '分区名称',
            'ys' => '省份名称',
            'yshi' => '城市名称',
            'xt' => '系统名称',
            'wd' => '网点名称',
            'name' => '导购姓名',
            'quitDate' => '离职生效日期',
            'applicant' => '申请人',
        ];
        $data = Db::table('bx_guide_apple_log')->alias('a')
            ->join('bx_guide_user b', 'a.apple_id = b.id')
            ->join('cg_net c', 'b.mainNet_id = c.id')
            ->join('cg_market_zoning p', 'c.zoning = p.id', 'LEFT')//营销区
            ->join('cg_market_provice n', 'c.provice = n.id', 'LEFT')//营销省
            ->join('cg_market_city o', 'c.city = o.id', 'LEFT')//营销市
            ->join('cg_system e', 'c.system_id = e.id', 'LEFT')//系统表
            ->field("a.no,a.theme,a.state,p.title yq,n.title ys,o.title yshi,e.title xt,c.title wd,
           b.name,b.quitDate,b.applicant")
            ->where('apple_name', 'bx_guide_quit')
            ->select();
        $data[] = [
            'title' => $str1,
            'sub' => $str,
        ];
        $excel = new ExcelDownload();
        $excel->exec($data, $titles, '所属导购离职查询', ['sheet' => ['rowHeight' => 20]], 3);
    }

    //导购人事日志
    //所属导购入职查询
    public function guideuserlog()
    {
        //查询条件
        $where = $this->request->post();
        $this->assign('where', $where);
        $where = self::str1($where);
        $page = empty($where['pages']) ? 1 : $where['pages'];
        $list = empty($where['limts']) ? 10 : $where['limts'];
        unset($where['pages']);
        unset($where['limts']);
        //总数量，总金额，总条数
        $count = Db::table('bx_guide_user_log')->alias('a')
            ->join('employee b', 'a.user_id = b.id')
            ->join('department_employee c', 'a.user_id = c.employee_id')
            ->join('department d', 'c.department_id = d.id')
            ->where($where)
            ->where('c.index', 1)
            ->count();
        $this->assign('count', $count);
        //分页
        $maxpage = ceil($count / $list);
        $page = $page < $maxpage ? $page : $maxpage;
        $page = $page > 1 ? $page : 1;
        $start = ($page - 1) * $list;
        $this->assign('page', $page);
        $this->assign('maxpage', $maxpage);
        $this->assign('limit', $list);
        //数据
        $data = Db::table('bx_guide_user_log')->alias('a')
            ->join('employee b', 'a.user_id = b.id')
            ->join('department_employee c', 'a.user_id = c.employee_id')
            ->join('department d', 'c.department_id = d.id')
            ->field("a.*,b.em_name,d.de_name")
            ->where($where)->order('a.id', 'desc')
            ->where('c.index', 1)
            ->limit($start, $list)
            ->select();
        $this->assign('data', $data);
        return $this->fetch();
    }

    //导购人事日志详情
    public function guideuserloginfo()
    {
        $id = $this->request->get('id');
        if ($id) {
            $data = Db::table('bx_guide_user_log')->alias('a')
                ->join('employee b', 'a.user_id = b.id')
                ->join('department_employee c', 'a.user_id = c.employee_id')
                ->join('department d', 'c.department_id = d.id')
                ->field("a.*,b.em_name,d.de_name")
                ->find();
            return json([
                'success' => true,
                'data' => $data
            ]);
        } else {
            return json([
                'success' => false,
                'msg' => '主键为空'
            ]);
        }
    }


    //导购薪酬管理
    public function guidewagesimport()
    {
        //查询条件
        $where = $this->request->post();
        $this->assign('where', $where);
        $where = self::str1($where);
        $page = empty($where['pages']) ? 1 : $where['pages'];
        $list = empty($where['limts']) ? 10 : $where['limts'];
        unset($where['pages']);
        unset($where['limts']);
        //总数量，总金额，总条数
        $count = Db::table('bx_guide_wages_log')->alias('a')
            ->where($where)
            ->count();
        $this->assign('count', $count);
        //分页
        $maxpage = ceil($count / $list);
        $page = $page < $maxpage ? $page : $maxpage;
        $page = $page > 1 ? $page : 1;
        $start = ($page - 1) * $list;
        $this->assign('page', $page);
        $this->assign('maxpage', $maxpage);
        $this->assign('limit', $list);
        //数据
        $data = Db::table('bx_guide_wages_log')
            ->where($where)->order('id', 'desc')
            ->limit($start, $list)
            ->select();
        $this->assign('data', $data);
//        $user = Db::table('employee')->where('id', session('employee_id'))->value('em_name');
        $date = Db::table('bx_guide_wages_log')->field('date,operator')->order('date', 'desc')->limit(1)->find();
        if (!$date) {
            $date = ['date' => '还没有更新', 'operator' => '还没有更新'];
        }
        $this->assign('date', $date);
        return $this->fetch();
    }


    //导入导购薪酬管理
    public
    function uploadwages()
    {
        // 获取表单上传文件
        $file = request()->file('file');
        // 移动到框架应用根目录/public/uploads/bx_wd 目录下
        $info = $file->validate(['ext' => 'xls,xlsx', 'size' => 105678])->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'bx_guide');
        if ($info) {
            //成功上传后 获取上传信息
            $data = self::testExcel3($info->getSaveName());
            if ($data['success'] == 'success') {
                echo "<script>top.sweetAlert('" . $data['msg'] . "','','" . $data['success'] . "');parent.location.reload();</script>";
            } else {
                echo "<script>top.sweetAlert('" . $data['msg'] . "','','" . $data['success'] . "');</script>";
            }
        } else {
            //上传失败获取错误信息
            echo "<script>top.sweetAlert('" . $file->getError() . "','','warning');</script>";
        }
    }

    /**
     * 导入导购薪酬管理
     */
    public
    function testExcel3($file)
    {
        $url = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'bx_guide' . DS . $file;
        $reader = new ExcelReader($url);
        $titlesMap = [
            'no' => '序号',
            'ny' => '月份',
            'name' => '姓名',
            'phone' => '电话',
            'IDNo' => '身份证',
            'city' => '所在城市',
            'wd' => '所在网点名称',
            'wd_no' => '所在网点编号',
            'money' => '金额（元）',
            'num' => '数量（支）',
            'basePay' => '基本工资',
            'mainItem' => '主品项',
            'nonMainItem' => '非主品项',
            'fare' => '车费',
            'fee' => '通讯费',
            'otherSub' => '其他补贴',
            'bonus' => '奖金',
            'overtimePay' => '加班工资',
            'shouldWages' => '应发工资',
            'fuJiLi' => '负激励',
            'kaoQinKouKuan' => '考勤扣款',
            'incomeTax' => '所得税',
            'sheBao' => '社保',
            'jianXiangCount' => '减项合计',
            'other1' => '其他1',
            'other2' => '其他2',
            'other3' => '其他3',
            'other4' => '其他4',
            'other5' => '其他5',
            'otherCount' => '其他合计',
            'payroll' => '实发工资',
            'des' => '备注',
        ];
        // 是否提供titlesMap 返回的数据结构不一致
        $data = $reader->exec();
        if ($data) {
            unset($data[0]);
            unset($data[1]);
            unset($data[2]);
            unset($data[3]);
            foreach ($data as $key => $val) {
                $is_empty = 0;
                foreach ($val as $k => $v) {
                    if (!trim($v)) {
                        $is_empty++;
                    }
                }
                if ($is_empty == count($val)) unset($data[$key]);
            }
            foreach ($data as $key => $val) {
                $tmp[] = array_combine(array_keys($titlesMap), $val);
            }
            if ($tmp) {
                //导购姓名
                $guideName = Db::table('bx_guide_user')->column('id,name');
                $guideName1 = implode(',', $guideName);
                //网点
                $wd = Db::table('cg_net')->field('id,sn,title')->select();
                $title4 = array_column($wd, 'title');
                $wd1 = implode(',', $title4);
                $wd_no = implode(',', array_column($wd, 'sn'));
                $wd2 = array_combine(array_column($wd, 'id'), $title4);
                $validate = new Validate([
                    ['no', 'require|integer', '导序号必须|序号必须是整数'],
                    ['ny', 'require|dateFormat:Y-m', '日期前必须|日期格式为年月'],
                    ['name', 'require|in:' . $guideName1, '导购姓名必须|导购姓名不存在'],
                    ['phone', 'require|regex:phone', '电话必须|电话格式不正确'],
                    ['IDNo', 'require|regex:chinaId', '身份证号码必须|身份证格式不正确'],
                    ['wd', 'require|in:' . $wd1, '网点名称必须|网点不存在'],
                    ['wd_no', 'require|in:' . $wd_no, '网点编号必须|网点编号不存在'],
                    ['money', 'require|number', '金额必须|金额为金额格式'],
                    ['num', 'require|number', '数量必须|数量为数字格式'],
                    ['basePay', 'require|number', '基本工资必须|基本工资为金额格式'],
                    ['mainItem', 'require|number', '主品项必须|主品项为金额格式'],
                    ['nonMainItem', 'require|number', '非主品项必须|非主品项为金额格式'],
                    ['fare', 'require|number', '车费必须|车费为金额格式'],
                    ['fee', 'require|number', '通讯费必须|通讯费为金额格式'],
                    ['otherSub', 'require|number', '其他补贴必须|其他补贴为金额格式'],
                    ['bonus', 'require|number', '奖金必须|奖金为金额格式'],
                    ['overtimePay', 'require|number', '其他补贴必须|其他补贴为金额格式'],
                    ['shouldWages', 'require|number', '应发工资必须|应发工资为金额格式'],
                    ['fuJiLi', 'require|number', '负激励必须|负激励为金额格式'],
                    ['kaoQinKouKuan', 'require|number', '考勤扣款必须|考勤扣款为金额格式'],
                    ['incomeTax', 'require|number', '所得税必须|所得税为金额格式'],
                    ['sheBao', 'require|number', '社保必须|社保为金额格式'],
                    ['jianXiangCount', 'require|number', '减项总和必须|减项总和为金额格式'],
                    ['other1', 'require|number', '其他1必须|其他1为金额格式'],
                    ['other2', 'require|number', '其他2必须|其他2为金额格式'],
                    ['other3', 'require|number', '其他3必须|其他3为金额格式'],
                    ['other4', 'require|number', '其他4必须|其他4为金额格式'],
                    ['other5', 'require|number', '其他5必须|其他5为金额格式'],
                    ['otherCount', 'require|number', '其他合计其他合计必须|其他合计为金额格式'],
                    ['payroll', 'require|number', '实发工资必须|实发工资为金额格式'],
                ]);
                $off = 1;
                $money = 0;
                foreach ($tmp as $key => $val) {
                    $tmp[$key]['wd_id'] = array_search($tmp[$key]['wd'], $wd2);
                    $tmp[$key]['user_id'] = array_search($tmp[$key]['name'], $guideName);
                    $money += $tmp[$key]['payroll'];
                    if ($validate->check($val)) {
                        $off = 1;
                    } else {
                        $off = 0;
                        break;
                    }
                }
                if ($off === 1) {
                    $log = [
                        'operator' => Db::table('employee')->where('id', session('employee_id'))->value('em_name'),
                        'log' => '导入了' . date('Y日m月') . '的发运数据',
                        'file' => $file,
                        'date' => date('Y-m-d H:i:s'),
                        'ny' => date('Y-m'),
                        'rows' => count($tmp),
                        'zmoney' => $money,
                    ];
                    if (Db::table('bx_guide_wages')->insertAll($tmp)) {
                        if (Db::table('bx_guide_wages_log')->insert($log)) {
                            return [
                                "success" => 'success',
                                'msg' => '上传文件成功'
                            ];
                        }
                    } else {
                        return [
                            "success" => 'warning',
                            'msg' => '网络错误！请重试'
                        ];
                    }
                } else {
                    return [
                        "success" => 'warning',
                        "msg" => $validate->getError()
                    ];
                }
            } else {
                return [
                    "success" => 'warning',
                    'msg' => '请填充数据'
                ];
            }
        } else {
            return [
                "success" => 'warning',
                'msg' => '网络错误！请重试'
            ];
        }
    }


    //导购工资查询
    public function guidewages()
    {
        //查询条件
        $where = $this->request->post();
        $this->assign('where', $where);
        $where = self::str1($where);
        $page = empty($where['pages']) ? 1 : $where['pages'];
        $list = empty($where['limts']) ? 10 : $where['limts'];
        unset($where['pages']);
        unset($where['limts']);
        //总数量，总金额，总条数
        $count = Db::table('bx_guide_wages')->alias('a')
            ->join('cg_net c', 'a.wd_id = c.id')
            ->join('cg_jxs d', 'c.jxs = d.id', 'LEFT')//经销商
            ->join('cg_market_zoning p', 'c.zoning = p.id', 'LEFT')//营销区
            ->join('cg_market_provice n', 'c.provice = n.id', 'LEFT')//营销省
            ->join('cg_market_city o', 'c.city = o.id', 'LEFT')//营销市
            ->join('cg_system e', 'c.system_id = e.id', 'LEFT')//系统表
            ->where($where)
            ->count();
        $this->assign('count', $count);
        //分页
        $maxpage = ceil($count / $list);
        $page = $page < $maxpage ? $page : $maxpage;
        $page = $page > 1 ? $page : 1;
        $start = ($page - 1) * $list;
        $this->assign('page', $page);
        $this->assign('maxpage', $maxpage);
        $this->assign('limit', $list);
        //数据
        $data = Db::table('bx_guide_wages')->alias('a')
            ->join('cg_net c', 'a.wd_id = c.id')
            ->join('cg_jxs d', 'c.jxs = d.id', 'LEFT')//经销商
            ->join('cg_market_zoning p', 'c.zoning = p.id', 'LEFT')//营销区
            ->join('cg_market_provice n', 'c.provice = n.id', 'LEFT')//营销省
            ->join('cg_market_city o', 'c.city = o.id', 'LEFT')//营销市
            ->join('cg_system e', 'c.system_id = e.id', 'LEFT')//系统表
            ->field("a.*,p.title yq,n.title ys,o.title yshi,e.title xt,d.title jxs,d.sn jxs_no,c.title wd,c.sn wd_no")
            ->where($where)->order('a.id', 'desc')
            ->limit($start, $list)
            ->select();
        $this->assign('data', $data);
        //总和
        $coun1 = Db::table('bx_guide_wages')->alias('a')
            ->join('cg_net c', 'a.wd_id = c.id')
            ->join('cg_jxs d', 'c.jxs = d.id', 'LEFT')//经销商
            ->join('cg_market_zoning p', 'c.zoning = p.id', 'LEFT')//营销区
            ->join('cg_market_provice n', 'c.provice = n.id', 'LEFT')//营销省
            ->join('cg_market_city o', 'c.city = o.id', 'LEFT')//营销市
            ->join('cg_system e', 'c.system_id = e.id', 'LEFT')//系统表
            ->where($where)->field('sum(a.money) money,sum(a.num) num,sum(a.basePay) basePay,
            sum(a.mainItem) mainItem,sum(a.nonMainItem) nonMainItem,sum(a.fare) fare,sum(a.fee) fee,
            sum(a.otherSub) otherSub,sum(a.bonus) bonus,sum(a.overtimePay) overtimePay,sum(a.shouldWages) shouldWages,
            sum(a.fuJiLi) fuJiLi,sum(a.kaoQinKouKuan) kaoQinKouKuan,sum(a.incomeTax) incomeTax,sum(a.sheBao) sheBao,
            sum(a.jianXiangCount) jianXiangCount,sum(a.other1) other1,sum(a.other2) other2,sum(a.other3) other3,
            sum(a.other4) other4,sum(a.other5) other5,sum(a.otherCount) otherCount,sum(a.payroll) payroll')->find();
        $this->assign('coun1', $coun1);
        return $this->fetch();
    }

    //导购工资导入日志
    public function wagesimportlog()
    {
        $where = $this->request->post();
        $this->assign('where', $where);
        $where = self::str1($where, 'date');
        $page = empty($where['pages']) ? 1 : $where['pages'];
        $list = empty($where['limts']) ? 10 : $where['limts'];
        unset($where['pages']);
        unset($where['limts']);
        //总条数
        $count = Db::table('bx_guide_wages_log')->where($where)->count();
        $this->assign('count', $count);
        //分页
        $maxpage = ceil($count / $list);
        $page = $page < $maxpage ? $page : $maxpage;
        $page = $page > 1 ? $page : 1;
        $start = ($page - 1) * $list;
        $this->assign('page', $page);
        $this->assign('maxpage', $maxpage);
        $this->assign('limit', $list);
        //数据
        $data = Db::table('bx_guide_wages_log')
            ->where($where)->order('id', 'desc')
            ->limit($start, $list)
            ->select();
        $this->assign('data', $data);
        return $this->fetch();
    }

    //导购档案
    public function guideInfo()
    {
        $id = $this->request->get('id');
        if ($id) {
            //人事类型
            $tingType = Db::table('bx_guide_thingtype')->alias('a')
                ->join('bx_guide_user c', 'a.user_id = c.id')
                ->join('cg_net b', 'c.mainNet_id = b.id', 'LEFT')
                ->join('cg_market_zoning p', 'b.zoning = p.id', 'LEFT')//营销区
                ->join('cg_market_provice n', 'b.provice = n.id', 'LEFT')//营销省
                ->join('cg_market_city o', 'b.city = o.id', 'LEFT')//营销市
                ->join('cg_system e', 'b.system_id = e.id', 'LEFT')//系统表
                ->join('bx_guide_salaryLevel d', 'c.salarylevel_id = d.id', 'LEFT')//薪资级别
                ->field("a.tingType,a.okDate,a.reason,concat(o.title,'-',e.title,'\-',b.title) wd,(case
            when c.postType = 0 then '全职'
            when c.postType = 1 then '兼职'
            when c.postType = 2 then '专职'
            end) postType,d.salaryLevel")
                ->where('a.user_id', $id)->select();
            $this->assign('tingType', $tingType);
            //信息
            $data = Db::table('bx_guide_user')->alias('a')
                ->join('cg_net b', 'a.mainNet_id = b.id', 'LEFT')
                ->join('cg_jxs d', 'b.jxs = d.id', 'LEFT')
                ->join('cg_market_zoning p', 'b.zoning = p.id', 'LEFT')//营销区
                ->join('cg_market_provice n', 'b.provice = n.id', 'LEFT')//营销省
                ->join('cg_market_city o', 'b.city = o.id', 'LEFT')//营销市
                ->join('cg_system e', 'b.system_id = e.id', 'LEFT')//系统表
                ->field("a.*,b.id wd_id,concat(o.title,'-',e.title,'\-',b.title) wd,
                b.sn wd_no,p.title yq,n.title ys,o.title yshi,e.title xt,d.title jxs")
                ->where('a.id', $id)->find();
            //更多所属网点
            $tmp = Db::table('cg_net')->where("id in (" . $data['otherNet_id'] . ")")->column('title');
            $data['otherNet'] = implode(',', $tmp);
            $str = ['在职', '试用', '离职'];
            $data['nowState'] = $str[$data['nowState']];
            $str1 = ['全职', '兼职', '专职'];
            $data['postType'] = $str1[$data['postType']];
            $str2 = ['金牌导购', '银牌导购', '普通导购'];
            $data['guideGrade'] = $str2[$data['guideGrade']];
            $this->assign('data', $data);
            //附件
            $file = new Ashippingmanagement2();
            $uploadify = $file->fileSelect($id, 'bx_guide_user');
            $this->assign('uploadify', $uploadify);
            //入离职记录
            $apple = Db::table('bx_guide_apple_log')
                ->where(['apple_id' => $id, 'apple_name' => 'bx_guide_user'])
                ->select();
            $quit = Db::table('bx_guide_apple_log')
                ->where(['apple_id' => $id, 'apple_name' => 'bx_guide_quit'])
                ->select();
            $this->assign('apple', $apple);
            $this->assign('quit', $quit);
            //异动记录
            $accident = Db::table('bx_guide_accident')->where('user_id', $id)->select();
            $this->assign('accident', $accident);
            //劳动合同
            $labourContract = Db::table('bx_guide_user')->alias('a')
                ->join('bx_guide_labour_contract b', 'a.id = b.BPartyName_id')
                ->join('cg_net c', 'a.mainNet_id = c.id', 'LEFT')
                ->field("b.id,b.indexes,b.contractName,b.BPartyName,(case 
            when a.postType = 0 then '全职'
            when a.postType = 1 then '兼职'
            when a.postType = 2 then '专职'
             end) postType,b.APartyName,a.mainNet_id,c.title mainNet,b.signDate,b.endDate,b.signNum,if(b.returnContract = 0,'x','√') returnContract,(case
            when a.nowState = 0 then '在职'
            when a.nowState = 1 then '使用'
            when a.nowState = 2 then '离职'
            end) state")
                ->where('a.id', $id)
                ->select();
            $this->assign('labourContract', $labourContract);
            return $this->fetch();
        } else {
            echo '主键错误！';
        }
    }

    //修改入离职时间
    public function editDate()
    {
        $data = $this->request->post();
        Db::table('bx_guide_user')->where('id', $data['id'])->update($data);
        return json([
            'success' => true
        ]);
    }

    //异动详情
    public function accidentInfo()
    {
        $id = $this->request->get('id');
        if ($id) {
            $data = Db::table('bx_guide_user')->alias('a')
                ->join('cg_net b', 'a.mainNet_id = b.id', 'LEFT')
                ->join('cg_jxs d', 'b.jxs = d.id', 'LEFT')
                ->join('cg_market_zoning p', 'b.zoning = p.id', 'LEFT')//营销区
                ->join('cg_market_provice n', 'b.provice = n.id', 'LEFT')//营销省
                ->join('cg_market_city o', 'b.city = o.id', 'LEFT')//营销市
                ->join('cg_system e', 'b.system_id = e.id', 'LEFT')//系统表
                ->field("a.*,concat(o.title,'-',e.title,'\-',b.title) wd,
                p.title yq,n.title ys,o.title yshi")
                ->where('a.id', $id)->find();
            //更多所属网点
            $tmp = Db::table('cg_net')->where("id in (" . $data['otherNet_id'] . ")")->column('title');
            $data['otherNet'] = implode(',', $tmp);
            $str1 = ['全职', '兼职', '专职'];
            $data['postType'] = $str1[$data['postType']];
            $year = date('Y', strtotime($data['birthDate']));
            $data['year'] = date('Y') - $year;
            $sub = Db::table('bx_guide_accident')->where('user_id', $id)->select();
            $this->assign('data', $data);
            $this->assign('sub', $sub);
            return $this->fetch();
        } else {
            echo '主键错误';
        }
    }

    //导出导购档案
    public function exportGuide()
    {
        $user = Db::table('employee')->where('id', session('employee_id'))->value('em_name');
        $str = '注：本表单由销路通软件导出，导出时间：' . date('Y-m-d H:i:s') . '；导出人：' . $user;
        $str1 = '导购档案';
//        $titles = ['姓名', '年龄', '性别', '身高'];
        // titles格式也可以如下
        $titles = [
            'name' => '姓名',
            'yq' => '网点所属分区',
            'ys' => '网点所属省份',
            'yshi' => '网点所属城市',
            'xt' => '系统名称',
            'wd' => '网点名称',
            'wdfz' => '网点负责人',
            'pjone' => '联系方式',
            'address' => '通讯地址',
            'IDNo' => '身份证号码',
            'address1' => '户籍地址',
            'state' => '目前状态',
            'quitDate' => '离职生效日',
            'id' => '巡检次数',
            'des' => '备注',
        ];
        $data[] = [
            'title' => $str1,
            'sub' => $str,
        ];
        $data = Db::table('bx_guide_user')->alias('a')
            ->join('cg_net b', 'a.mainNet_id = b.id')
            ->join('cg_market_zoning p', 'b.zoning = p.id', 'LEFT')//营销区
            ->join('cg_market_provice n', 'b.provice = n.id', 'LEFT')//营销省
            ->join('cg_market_city o', 'b.city = o.id', 'LEFT')//营销市
            ->join('cg_system e', 'b.system_id = e.id', 'LEFT')//系统表
            ->field("a.name,p.title yq,n.title ys,o.title yshi,e.title xt,b.title wd,b.stuff wdfz,
            a.phone,CONCAT(a.livingProvince,'-',a.livingCity,'-',a.livingCounty,'-',a.livingAddress) address,
            a.IDNo,CONCAT(a.houseProvince,'-',a.houseCity,'-',a.houseCounty,'-',a.houseAddress) address1,(case
            when a.nowState = 0 then '在职'
            when a.nowState = 1 then '使用'
            when a.nowState = 2 then '离职'
            end) state,a.quitDate,a.id,a.des")
            ->select();
        foreach ($data as $key => $val) {
            if ($val['wdfz']) {
                $data[$key]['wdfz'] = implode(',', Db::name('employee')->where("id in (" . implode(',', unserialize($val['wdfz'])) . ")")->column('em_name'));
            }
        }
        $excel = new ExcelDownload();
        $excel->exec($data, $titles, '导购档案', ['sheet' => ['rowHeight' => 20]], 3);
    }

    //导入导购档案文件
    public
    function importguide()
    {
        return $this->fetch();
    }

    //导入导购档案
    public
    function uploadGuidePost()
    {
        // 获取表单上传文件
        $file = request()->file('file');
        // 移动到框架应用根目录/public/uploads/bx_wd 目录下
        $info = $file->validate(['ext' => 'xls,xlsx', 'size' => 105678])->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'bx_guide');
        if ($info) {
            //成功上传后 获取上传信息
            $data = self::testExcelGuide($info->getSaveName());
            if ($data['success'] == 'success') {
                echo "<script>top.sweetAlert('" . $data['msg'] . "','','" . $data['success'] . "');</script>";
            } else {
                echo "<script>top.sweetAlert('" . $data['msg'] . "','','" . $data['success'] . "');</script>";
            }
        } else {
            //上传失败获取错误信息
            echo "<script>top.sweetAlert('" . $file->getError() . "','','warning');</script>";
        }
    }

    /**
     * excel导入示例
     */
    public
    function testExcelGuide($file)
    {
        $url = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'bx_guide' . DS . $file;
        $reader = new ExcelReader($url);
        $titlesMap = [
            'op' => '操作',
            'fileNo' => '档案编号',
            'workNumber' => '工卡号码',
            'name' => '姓名',
            'nation' => '民族',
            'sex' => '性别',//0=男，1=女
            'jiguan' => '籍贯（省市）',
            'birthDate' => '出生日期',
            'hunyinState' => '婚姻状况',//0,1
            'zinvSate' => '子女情况',//0,1
            'phone' => '手机号',
            'email' => '电子邮箱',
            'otherPhone' => '其他联系方式',
            'IDNo' => '身份证号码',
            'IDNoDate' => '身份证有效期',
            'IDNoOffice' => '身份证签发机关',
            'IDNoAddress' => '身份证地址',
            'houseType' => '户口性质',//0=农村，1=城市
            'houseAddress' => '户籍地址',
            'livingAddress' => '现住地址',
            'workAddress' => '工作长驻地（城市）',
            'openingBank' => '开户银行',
            'bankAccount' => '银行账号',
            'urgentLinkman' => '紧急联系人',
            'urgentTel' => '联络人电话',
            'urgentAddress' => '联络人地址',
            'postalCode' => '邮政编码',
            'entryDate' => '入职日期',
            'justDate' => '转正日期',
            'department' => '部门',
            'post' => '岗位',
            'isFirstBoss' => '是否为部门第一负责人',//0,1
            'duiyngshengfen' => '对应省份',
            'postType' => '用工性质',//0,1,2
            'fanPin' => '是够允许返聘',//1是，0否
            'nowState' => '目前在职状态',//0,1,2
            'pinyongType' => '聘用形式',
            'signContract' => '是否签订劳动合同',//1是，0否
            'referee' => '招聘人',//referee_id
            'recruitmentChannels' => '招聘地城市',
            'isDanbao' => '是否有担保',
            'zuigaoxueli' => '最高学历',
            'biyeDate' => '毕业时间',
            'aspeciaiHobby' => '特长爱好',
            'des' => '备注',
        ];
        // 是否提供titlesMap 返回的数据结构不一致
        $data = $reader->exec();
        if ($data) {
            unset($data[0]);
            unset($data[1]);
            unset($data[2]);
            foreach ($data as $key => $val) {
                $is_empty = 0;
                foreach ($val as $k => $v) {
                    if (!trim($v)) {
                        $is_empty++;
                    }
                }
                if ($is_empty == count($val)) unset($data[$key]);
            }

            foreach ($data as $key => $val) {
                $tmp[] = array_combine(array_keys($titlesMap), $val);
            }
            if ($tmp) {
                //姓名不能重复
                $name = Db::table('bx_guide_user')->column('id,name');
                $name1 = implode(',', $name);
                //性别0,1
                $sex = ['男', '女'];
                $sex1 = implode(',', $sex);
                //婚姻情况0，1
                $hunyinState = ['否', '是'];
                $hunyinState1 = implode(',', $hunyinState);
                //子女情况0,1
                $zinvSate = ['无', '有'];
                $zinvSate1 = implode(',', $zinvSate);
                //户口性质0,1
                $houseType = ['农村户口', '城市户口'];
                $houseType1 = implode(',', $houseType);
                //部门
                $department = Db::table('department')->column('id,de_name');
                $department1 = implode(',', $department);
                //岗位job
                $post = Db::table('job')->column('id,job_name');
                $post1 = implode(',', $post);
                //用工性质
                $postType = ['全职', '兼职', '专职'];
                $postType1 = implode(',', $postType);
                //目前状态
                $nowState = ['在职', '试用', '离职'];
                $nowState1 = implode(',', $nowState);
                //招聘人
                $referee = Db::table('employee')->column('id,em_name');
                $referee1 = implode(',', $referee);
                $validate = new Validate([
                    ['op', 'require', '操作必须'],
                    ['fileNo', 'require', '档案编号必须'],
                    ['name', 'require|notIn:' . $name1, '姓名必须|姓名已存在'],
                    ['nation', 'require', '民族必须'],
                    ['sex', 'require|in:' . $sex1, '性别必须|性别为男或女'],
                    ['birthDate', 'date', '出生日期时间格式'],
                    ['hunyinState', 'require|in:' . $hunyinState1, '婚姻情况必须|婚姻情况为是或否'],
                    ['zinvSate', 'require|in:' . $zinvSate1, '子女情况必须|子女情况为有或无'],
                    ['phone', 'require|regex:phone', '电话必须|电话格式不正确'],
                    ['email', 'email', '邮箱格式不正确'],
                    ['IDNo', 'require|regex:chinaId', '身份证号码必须|身份证格式不正确'],
                    ['IDNoDate', 'date', '身份证有效期时间格式'],
                    ['houseType', 'in:' . $houseType1, '户口性质为农村或城镇'],
                    ['entryDate', 'require|date', '入职日期必须|入职日期时间格式'],
                    ['justDate', 'require|date', '转正日期必须|转正日期时间格式'],
                    ['department', 'require|in:' . $department1, '部门必须|部门时间格式不存在'],
                    ['post', 'require|in:' . $post1, '岗位必须|岗位不存在'],
                    ['isFirstBoss', 'require|in:' . $hunyinState1, '是否部门第一负责人必须|是否部门第一负责人为是或否'],
                    ['postType', 'in:' . $postType1, '用工类型为全职或兼职'],
                    ['fanPin', 'in:' . $hunyinState1, '是否允许返聘'],
                    ['nowState', 'require|in:' . $nowState1, '目前状态必须|目前状态必须为在职等'],
                    ['signContract', 'require|in:' . $hunyinState1, '是否签订合同必须|是否签订合同必须为是否'],
                    ['isDanbao', 'in:' . $zinvSate1, '是否有无担保为有无'],
                    ['referee', 'in:' . $referee1, '招聘人不存在'],
                    ['biyeDate', 'date', '毕业时间为时间格式'],
                ]);
                $off = 1;
                foreach ($tmp as $key => $val) {
                    $tmp[$key]['sex'] = array_search($val['sex'], $sex);
                    $tmp[$key]['hunyinState'] = array_search($val['hunyinState'], $hunyinState);
                    $tmp[$key]['isFirstBoss'] = array_search($val['isFirstBoss'], $hunyinState);
                    $tmp[$key]['fanPin'] = array_search($val['fanPin'], $hunyinState);
                    $tmp[$key]['signContract'] = array_search($val['signContract'], $hunyinState);
                    $tmp[$key]['zinvSate'] = array_search($val['zinvSate'], $zinvSate);
                    $tmp[$key]['isDanbao'] = array_search($val['isDanbao'], $zinvSate);
                    $tmp[$key]['houseType'] = array_search($val['houseType'], $houseType);
                    $tmp[$key]['postType'] = array_search($val['postType'], $postType);
                    $tmp[$key]['nowState'] = array_search($val['nowState'], $nowState);
                    $tmp[$key]['referee_id'] = array_search($val['referee'], $referee);
                    if ($validate->check($val)) {
                        $off = 1;
                    } else {
                        $off = 0;
                        break;
                    }
                }
                if ($off === 1) {
                    if (Db::table('bx_guide_user')->insertAll($tmp)) {
                        return [
                            "success" => 'success',
                            'msg' => '上传文件成功'
                        ];
                    } else {
                        return [
                            "success" => 'warning',
                            'msg' => '网络错误！请重试'
                        ];
                    }
                } else {
                    return [
                        "success" => 'warning',
                        "msg" => $validate->getError()
                    ];
                }
            } else {
                return [
                    "success" => 'warning',
                    'msg' => '请填充数据'
                ];
            }
        } else {
            return [
                "success" => 'warning',
                'msg' => '网络错误！请重试'
            ];
        }
    }

    public function exportAllGuide()
    {
        $user = Db::table('employee')->where('id', session('employee_id'))->value('em_name');
        $str = '注：本表单由销路通软件导出，导出时间：' . date('Y-m-d H:i:s') . '；导出人：' . $user;
        $str1 = '导购档案汇总';
//        $titles = ['姓名', '年龄', '性别', '身高'];
        // titles格式也可以如下
        $titles = [
            'No. ' => '序号',
            'fileNo' => '档案编号',
            'workNumber' => '工卡号码',
            'name' => '姓名',
            'nation' => '民族',
            'sex' => '性别',//0=男，1=女
            'jiguan' => '籍贯（省市）',
            'birthDate' => '出生日期',
            'hunyinState' => '婚姻状况',//0,1
            'zinvSate' => '子女情况',//0,1
            'phone' => '手机号',
            'email' => '电子邮箱',
            'otherPhone' => '其他联系方式',
            'IDNo' => '身份证号码',
            'IDNoDate' => '身份证有效期',
            'IDNoOffice' => '身份证签发机关',
            'IDNoAddress' => '身份证地址',
            'houseType' => '户口性质',//0=农村，1=城市
            'houseAddress' => '户籍地址',
            'livingAddress' => '现住地址',
            'workAddress' => '工作长驻地（城市）',
            'openingBank' => '开户银行',
            'bankAccount' => '银行账号',
            'urgentLinkman' => '紧急联系人',
            'urgentTel' => '联络人电话',
            'urgentAddress' => '联络人地址',
            'postalCode' => '邮政编码',
            'entryDate' => '入职日期',
            'justDate' => '转正日期',
            'department' => '部门',
            'post' => '岗位',
            'firstBoss' => '是否为部门第一负责人',//0,1
            'duiyngshengfen' => '对应省份',
            'postType' => '用工性质',//0,1,2
            'fanPin' => '是够允许返聘',//1是，0否
            'nowState' => '目前在职状态',//0,1,2
            'pinyongType' => '聘用形式',
            'signContract' => '是否签订劳动合同',//1是，0否
            'referee' => '招聘人',//referee_id
            'recruitmentChannels' => '招聘地城市',
            'isDanbao' => '是否有担保',
            'zuigaoxueli' => '最高学历',
            'biyeDate' => '毕业时间',
            'aspeciaiHobby' => '特长爱好',
            'des' => '备注',
        ];
        Db::table('bx_guide_user')->query("set @i = 0");
        $data = Db::table('bx_guide_user')
            ->field("(@i:=@i+1) No,fileNo,workNumber,name,nation,if(sex = 1,'女','男') sex,jiguan,birthDate,
            if(hunyinState=1,'是','否') hunyinState,
            if(zinvSate=1,'有','无') zinvSate,phone,email,
            otherPhone,IDNo,IDNoDate,IDNoOffice,IDNoAddress,if(houseType=0,'农村户口','城市户口') houseType,houseAddress,livingAddress,
            workAddress,openingBank,bankAccount,urgentLinkman,urgentTel,urgentAddress,postalCode,
            entryDate,justDate,department,post,(case 
             when isFirstBoss = 0  then '否'
             when isFirstBoss = 1  then '是'
             end) isFirstBoss,duiyngshengfen,(CASE 
             when postType = 0 then '全职'
             when postType = 1 then '兼职'
             when postType = 2 then '专职'
             END) postType,if(fanPin=0,'否','是') fanPin,
            (CASE 
             when nowState = 0 then '在职'
             when nowState = 1 then '试用'
             when nowState = 2 then '离职'
             END) nowState,
            pinyongType,(case
             when signContract=0 then '否'
             when signContract=1 then '是'
             end) signContract,referee,recruitmentChannels,isDanbao,zuigaoxueli,biyeDate,
            aspeciaiHobby,des")
            ->select();
        if ($data) {
            $data[] = [
                'title' => $str1,
                'sub' => $str,
            ];
            $excel = new ExcelDownload();
            $excel->exec($data, $titles, '导购档案汇总', ['sheet' => ['rowHeight' => 20]], 3);
        } else {
            echo "<script>top.sweetAlert('没有数据','','warning');history.go(-1);</script>";
        }
    }

    //导购销售目标格式
    public function guideformat()
    {
        //查询条件
        $where = $this->request->post();
        $this->assign('where', $where);
        $where = self::str1($where);
        $page = empty($where['pages']) ? 1 : $where['pages'];
        $list = empty($where['limts']) ? 10 : $where['limts'];
        unset($where['pages']);
        unset($where['limts']);
        //总数量，总金额，总条数
        $count = Db::table('bx_guide_format')->alias('a')
            ->join('employee b', 'a.createUser_id = b.id')
            ->where($where)
            ->count();
        $this->assign('count', $count);
        //分页
        $maxpage = ceil($count / $list);
        $page = $page < $maxpage ? $page : $maxpage;
        $page = $page > 1 ? $page : 1;
        $start = ($page - 1) * $list;
        $this->assign('page', $page);
        $this->assign('maxpage', $maxpage);
        $this->assign('limit', $list);
        //数据
        $data = Db::table('bx_guide_format')->alias('a')
            ->join('employee b', 'a.createUser_id = b.id')
            ->field('a.*,b.em_name createUser')
            ->where($where)->order('a.id', 'desc')
            ->limit($start, $list)
            ->select();
        $this->assign('data', $data);
        return $this->fetch();
    }

    //新增导购目标格式
    public function addformat()
    {
        return $this->fetch();
    }

    //新增导购目标格式form
    public function addformatform()
    {
        $data = $this->request->post();
        $data['createUser_id'] = session('employee_id');
        $data['createDate'] = date('Y-m-d');
        $year = implode(',', Db::table('bx_guide_format')->column('year'));
        $validate = new Validate([
            ['year', 'require|notIn:' . $year, '财年必须|财年已存在'],
        ]);
        if ($validate->check($data)) {
            if (Db::table('bx_guide_format')->insert($data)) {
                return json([
                    'success' => true,
                ]);
            };
        } else {
            return [
                "success" => false,
                "msg" => $validate->getError()
            ];
        }

    }

    //修改导购目标格式
    public function editformat()
    {
        $id = $this->request->get('id');
        if ($id) {
            $data = Db::table('bx_guide_format')->where('id', $id)->find();
            $this->assign('data', $data);
            return $this->fetch();
        } else {
            echo '主键错误！';
        }
    }

    //修改导购目标格式form
    public function editformatform()
    {
        $data = $this->request->post();
        if ($data['id']) {
            Db::table('bx_guide_format')->where('id', $data['id'])->update($data);
            return json([
                'success' => true,
            ]);
        } else {
            echo '主键错误！';
        }
    }

    /**
     * @param $data //数组
     */
    public function makeExcel()
    {
        $id = $this->request->get('id');
        if ($id) {
            $data = Db::table('bx_guide_format')->where('id', $id)->find();
            $title[] = '导购员姓名';
            $content[] = '必填项。';
            if ($data['wd_dimension']) {
                $title[] = '网点名称';
                $content[] = '必填项。必须是销路通系统中已存在的网点名称';
            }
            if ($data['cp_dimension']) {
                $type = ['品牌', '品类', '系列', 'SKU', '单品'];
                $title[] = '产品' . $type[$data['cp_type']];
                $content[] = '必填项。必须是销路通系统中已存在的产品' . $type[$data['cp_type']];
            }
            $kh = ['一级考核期', '二级考核期'];//kh_dimension
            $title[] = $kh[$data['kh_dimension']];
            $content[] = '必填项。必须是销路通系统中已存在的' . $kh[$data['kh_dimension']] . '，且该' . $kh[$data['kh_dimension']] . '属于财年';
            $title[] = '销售目标金额(元)';
            $content[] = '必填项';
            //表格title
            $excel = ['title' => $title, 'content' => $content];
            $this->excel($excel);
        } else {
            echo '主键错误！';
        }
    }

    //导出excel
    public function excel($data)
    {


        Vendor("PHPExcel");
        Vendor("PHPExcel.Writer.Excel5");
        // Loader::import('PHPExcel.Classes.PHPExcel');
        //Loader::import('PHPExcel.Classes.PHPExcel.IOFactory.PHPExcel_IOFactory');
        //  Vendor("Excel.PHPExcel.Writer.Excel2007");
        $objPHPExcel = new PHPExcel();


        $objProps = $objPHPExcel->getProperties();

        $objProps->setCreator('admin');
        $objProps->setLastModifiedBy('admin');
        $objProps->setTitle('Office 2003 XLSX Test Document');
        $objProps->setSubject('Office 2003 XLSX Test Document');
        $objProps->setDescription("Test document, generated by PHPExcel.");
        $objProps->setKeywords("office excel PHPExcel");
        $objProps->setCategory("Test");

        $objPHPExcel->setActiveSheetIndex(0);
//        $objPHPExcel->getActiveSheet()->setTitle($title);

        for ($i = 0; $i < count($data["content"]); $i++) {
            $objPHPExcel->getActiveSheet()->setCellValue(chr($i + 97) . '1', $data["title"][$i]);

            //加粗
            $objPHPExcel->getActiveSheet()->getStyle(chr($i + 97) . '1')->getFont()->setBold(true);
            //水平剧中
            $objPHPExcel->getActiveSheet()->getStyle(chr($i + 97) . '1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            //垂直剧中
            $objPHPExcel->getActiveSheet()->getStyle(chr($i + 97) . '1')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
            //填充背景色
            $objPHPExcel->getActiveSheet()->getStyle(chr($i + 97) . '1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
            $objPHPExcel->getActiveSheet()->getStyle(chr($i + 97) . '1')->getFill()->getStartColor()->setARGB('00ff3322');

            $objPHPExcel->getActiveSheet()->getStyle(chr($i + 97) . '1')->getAlignment()->setWrapText(true);


            $objPHPExcel->getActiveSheet()->setCellValue(chr($i + 97) . '2', $data["content"][$i]);
            //水平剧中
            $objPHPExcel->getActiveSheet()->getStyle(chr($i + 97) . '2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            //垂直剧中
            $objPHPExcel->getActiveSheet()->getStyle(chr($i + 97) . '2')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);

            //填充背景色
            $objPHPExcel->getActiveSheet()->getStyle(chr($i + 97) . '2')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
            $objPHPExcel->getActiveSheet()->getStyle(chr($i + 97) . '2')->getFill()->getStartColor()->setARGB('00FFFF00');

            $objPHPExcel->getActiveSheet()->getStyle(chr($i + 97) . '2')->getAlignment()->setWrapText(true);
            //设置宽度
            $objPHPExcel->getActiveSheet()->getColumnDimension(chr($i + 97))->setWidth(30);

        }

        //设置高度
        $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(30);
        $objPHPExcel->getActiveSheet()->getRowDimension('2')->setRowHeight(50);
        for ($i = 0; $i <= 20; $i++) {
            $h = 'A' . ($i + 3);
            $objPHPExcel->getActiveSheet()->setCellValue($h, " ");
        }
        //***********************画出单元格边框*****************************
        $styleArray = array(
            'borders' => array(
                'allborders' => array(
                    //'style' => PHPExcel_Style_Border::BORDER_THICK,//边框是粗的
                    'style' => PHPExcel_Style_Border::BORDER_THIN,//细边框
                    //'color' => array('argb' => 'FFFF0000'),
                ),
            ),
        );
        $objPHPExcel->getActiveSheet()->getStyle('A1:' . chr(96 + count($data["content"])) . '2')->applyFromArray($styleArray);//这里就是画出从单元格A5到N5的边框，看单元格最右边在哪哪个格就把这个N改为那个字母替代
//***********************画出单元格边框结束*****************************
        $objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
        ob_end_clean();
        //var_dump($objWriter);exit;
        header("Pragma: public");
        header("Expires:0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        header('Content-Disposition:attachment;filename=file.xls');
        header("Content-type:text/html;charset=utf-8");
        header("Content-Transfer-Encoding:binary");
        $objWriter->save('php://output');
    }

    public function aa()
    {
        $str = 'AQ__++_2009 弃我而去 二翁日文正则';
        $str = preg_replace('# #', '', $str);
        $arr = preg_split('/(?<!^)(?!$)/u', $str);
        $str1 = '';
        foreach ($arr as $key => $val) {
//            if (preg_match("/[ '.,:;*?_~`!@#$%^&+=)(<>{}]|\]|\[|\/|\\\|\"|\|/", $val)) {
//                unset($arr[$key]);
//            }
            if (preg_match("/[A-Za-z0-9-.,:;*?_~`!@#$%^&+=]+$/", $val)) {
                $str1 .= $val;
                unset($arr[$key]);
            }
        }
        $arr[] = $str1;
        p($arr);
        $arr = implode('', $arr) . '%';


        //二维数组字典排序
//        $data = [
//            [
//                'id' => '1',
//                'title' => 'B跨界十点发的',
//            ],
//            [
//                'id' => '2',
//                'title' =>  'D而为',
//            ],
//            [
//                'id' => '4',
//                'title' =>  'A1是的',
//            ],
//            [
//                'id' => '5',
//                'title' =>   'C1是3',
//            ]
//        ];
//       foreach ($data as $key => $val){
//           $title[] = $val['title'];
//       }
//       array_multisort($title,SORT_ASC,$data);
//       p($data);
        $str = '2018-05-15 10:11:50';//最后下载时间
        $str1 = date('Y-m-d H:i:s', strtotime("$str +1 day"));
        if ($str1 >= date('Y-m-d H:i:s')) {
            p('24小时未到');
        } else {
            p('24小时过了');
        }
    }
}
